Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 982
Md Shihab Uddin Avatar asked Apr 25 '17 04:04

Md Shihab Uddin


2 Answers

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.

like image 181
Nikita Koksharov Avatar answered Sep 20 '22 00:09

Nikita Koksharov


It seems you need application-level lock to ensure thread-safe operations from different application scopes which is pretty much same as distributed lock. For Jedis, a quick search yields Jedis-lock library.

Jedis jedis = new Jedis("localhost");
JedisLock lock = new JedisLock(jedis, "lockname", 10000, 30000);
lock.acquire();
try {
  // do some stuff
}
finally {
  lock.release();
}

System.out.println(jedis.isLocked());
System.out.println(jedis.isRemoteLocked());

Edit

According to Jedis-lock's owner (Thanks for this project), the project is no longer maintained/pull requests are not merged anymore. This fork is now actively maintained and has new features:

  • New SET API in place of old SETNX
  • Lock ownership safety using atomic LUA scripting on release()
  • Locking support for JedisCluster
like image 41
Kaidul Avatar answered Sep 20 '22 00:09

Kaidul