Search code examples
javaredisjedisdistributed-lock

How to lock redis cluster for an application in java


I've two java applications (app1, app2). Both applications are using JedisCluster client for Redis cluster. app1 write or read data from Redis cluster. app2 is like a scheduler which only writes some data to Redis cluster. it runs after a fixed time of interval. I've to ensure that when app2 is doing write operation, no data is served or written for app1 until the whole write operation is finished by app2. I want to lock Redis cluster for app1 when app2 is running. it doesn't matter whether app1 get an exception or not at that time.


Solution

  • Have you tried Redisson's lock? It's a Redis based framework.

    It offers Lock object implemented java.util.concurrent.locks.Lock interface and easy to use.

    RedissonClient redisson = Redisson.create(config);
    
    RLock lock = redisson.getLock("myLock");
    lock.lock();
    try {
       // ...
    } finally {
       lock.unlock();
    }
    

    It also offers Asynchronous version of lock object.