Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node Redis - SET with EX and NX?

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?

like image 228
Courtney Miles Avatar asked Apr 07 '13 10:04

Courtney Miles


1 Answers

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) {...});
like image 185
Courtney Miles Avatar answered Sep 23 '22 05:09

Courtney Miles