Redis queue used by various services ( create a lock to )

111 Views Asked by At

I'm using the Reddison client in a Java Spring Boot application.

I need to re-use a value (it's just a string) among all the members of the service. I'm thinking of using a Queue. When a service stops using the value, it puts it back in the queue, when a new service needs a value it takes it from the queue.

I'm trying to figure out how to read the value without several nodes pick up the same one. I don't couldn't find a way to create a lock and then release it.

I'm trying the following:

// When done using the value: 
Queue<String> q = redis.getQueue(KEY);
q.offer(value);
//when need a value;
Queue<String> q = redis.getQueue(KEY);
q.poll();

But this code runs on all the nodes, so, how can I guarantee 10 of them don't get the same value when I call poll

I see the client has a redis.createTransaction(options) method that could return a transaction but it doesn't allow to get a queue.

1

There are 1 best solutions below

0
OscarRyz On

I found out I can acquire a lock with 8. Distributed locks and synchronizers

RLock lock = redisson.getLock("myLock");

// traditional lock method
lock.lock();

// or acquire lock and automatically unlock it after 10 seconds
lock.lock(10, TimeUnit.SECONDS);

// or wait for lock aquisition up to 100 seconds 
// and automatically unlock it after 10 seconds
boolean res = lock.tryLock(100, 10, TimeUnit.SECONDS);
if (res) {
   try {
     ...
   } finally {
       lock.unlock();
   }
}

But now I wonder if I have to do it? @Mar-Z mentions they are not needed, but I can't find a reference to confirm it, but this is the answer to my question (how to get a lock)