jeudi 18 janvier 2018

Ruby REDIS with EX AND NX

I am trying to implement a locking in our rails application server.

REDIS.setnx works fine if I want to acquire a lock forever. But I want to acquire lock with expiry, basically I want the lock to expire after certain duration so that lock will be free to be acquired again.

From REDIS's set documentation, I see it is possible. http://ift.tt/2hsU2s5 "The command SET resource-name anystring NX EX max-lock-time is a simple way to implement a locking system with Redis."

How to implement this in ruby. Command :

REDIS = Redis.new(host: ENV['REDIS_HOST'], port: ENV['REDIS_PORT'])
REDIS.set "key", "value", "nx", "ex", 3600

throws error:

ArgumentError: wrong number of arguments (given 5, expected 2..3)

There is another way to do that, but it requires two REDIS calls.

if(REDIS.setnx "key", "value")
    REDIS.setex "key", 3600, "value"
end

This method is not preferred. I am looking to a way to acquire REDIS lock with single REDIS call in ruby. Basically "SET resource-name anystring NX EX max-lock-time" equivalent in ruby.

Thanks,

Anshul

Aucun commentaire:

Enregistrer un commentaire