redislock by Daniel St. Jules is a module for distributed locking powered by Redis. This utility is very helpful when you are building a distributed application, or even a basic CPU cluster to take advantage of multiple cores. One of the cool features is ability to set maximum number of retries and amount of time between them.
1
|
npm install redislock |
Usage
Locking is performed using the following redis command:
1
|
SET key uuid PX timeout NX |
If the SET returns OK, the lock has been acquired on the given key, and an expiration has been set. Then, releasing a lock uses the following redis script:
1
2
3
4
|
if redis.call( 'GET' , KEYS[1]) == ARGV[1] then return redis.call( 'DEL' , KEYS[1]) end return 0 |
This ensures that the key is deleted only if it is currently holding the lock, by passing its UUID as an argument.
Example below creates a lock and then tries to acquire it second time. The second attempt will fail.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
var redis = require( 'redis' ); var redislock = require( 'redislock' ); var client = redis.createClient(); var lock = redislock.createLock(client, { timeout: 20000, retries: 3, delay: 100 }); function doStuff(done) { lock.acquire( 'my:lock-name' , function (err) { if (err) { console.log( 'Failed to get a lock...' , err.message); return ; } // tring to get the same lock second time will trigger an error. doStuff(done); lock.release( function (err) { console.log( 'Do work here...' ); done(); }); }); } doStuff( function () { console.log( 'Done working...' ); client.end(); }); |