Manshavi Kumar
Manshavi Kumar

Reputation: 133

Redis Lock key in java

I am using Redis in my java project where i need to get the value of a key then do some modification and then again set the value of that key. My requirement is that if one thread got the value of a key then another thread should wait until the first thread set the value for that key. I could have used synchronised but we are using multiple server in our project so synchronised won't work for this condition. Can anyone suggest me some other solution for this condition.

Upvotes: 2

Views: 9594

Answers (1)

Redisson_RuiGu
Redisson_RuiGu

Reputation: 1032

I think Redisson project is the perfect solution for you.

Disclaimer: I am a member of Redisson project

Redisson understands the need to have a more abstract way to work with redis, so we have created many objects and services that work on top of your own redis and exposes standard java interfaces. All those objects and services are distributed and thread safe.

To solve your problem, we have plenty locks and synchronisers for you to choose from: Lock(ReentrantLock), FairLock, MultiLock, RedLock(as describe in the official document, and yes we have read it all), ReadWriteLock, Semaphore, PermitExpirableSemaphore, CountDownLatch.

The usage can't be more simple:

Node1:

Config config = ;//create your own configuration object based on connections types
RedissonClient redisson = Redisson.create(config);

//The Lock is just a java.util.concurrent.locks.Lock
Lock lock = redisson.getLock("myLock");
lock.lock();

//or if you want to have a lease time on the lock
((RLock) lock).lock(10, TimeUnit.SECONDS);

//do other business here.
lock.unlock();

Node2:

//The same as node1

If you would like to know a bit more please head to our website at https://redisson.org

Upvotes: 6

Related Questions