Redis recommends a method of using SET
with optional parameters as a locking mechanism. I.e. SET lock 1 EX 10 NX
will set a lock only if it does not already exists and it will expire after 10 second.
I'm using Node Redis, which has a set()
method, but I'm not sure how to pass it the additional parameters to have the key expire and not be created if it already exists, or even if it's possible.
Perhaps I have to use setnx()
and expire()
as separate calls?
After reading the Node Redis source code, I found that all methods accept an arbitrary number of arguments. When an error about incorrect number of arguments is generated, this is generated by Redis not the node module.
My early attempts to supply multiple arguments were because I only had Redis 2.2.x installed, where SET only accepts the NX and EX arguments with 2.6.12.
So with Redis 2.6.12 installed, the follow method calls will work with node redis to set a variable if it doesn't exist and set it to expire after 5 minutes:
$client->set('hello', 'world', 'NX', 'EX', 300, function(err, reply) {...});
$client->set(['hello', 'world', 'NX', 'EX', 300], function(err, reply) {...});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With