Battle-hardened distributed locking using redis.
- node-redis compatible with
v0.10 - Redis
v2.6.12or above. If you're running a Redis version fromv2.6.0tov2.6.11inclusive usev0.0.7of this module.
npm install node-redis-warlock
constWarlock=require('node-redis-warlock');constRedis=require('redis');// Establish a redis client and pass it to warlockconstredis=Redis.createClient();constwarlock=Warlock(redis);// Set a lockconstkey='test-lock';constttl=10000;// Lifetime of the lockwarlock.lock(key,ttl,(err,unlock)=>{if(err){// Something went wrong and we weren't able to set a lockreturn;}if(typeofunlock==='function'){// If the lock is set successfully by this process, an unlock function is passed to our callback.// Do the work that required lock protection, and then unlock() when finished...//// do stuff...//unlock();}else{// Otherwise, the lock was not established by us so we must decide what to do// Perhaps wait a bit & retry...}});// set a lock optimisticallyconstkey='opt-lock';constttl=10000;constmaxAttempts=4;// Max number of times to try setting the lock before erroringconstwait=1000;// Time to wait before another attempt if lock already in placewarlock.optimistic(key,ttl,maxAttempts,wait,(err,unlock)=>{});// unlock using the lock idvarkey='test-lock-2';varttl=10000;letlockId;warlock.lock(key,ttl,(err,_,id)=>{lockId=id;});// each client who knows the lockId can release the lockwarlock.unlock(key,lockId,(err,result)=>{if(result==1){// unlocked successfully}});// change a lock's ttlvarkey='touch-lock';varttl=10000;varttl2=20000;warlock.lock(key,ttl,function(err,unlock,id){warlock.touch(key,id,ttl2,function(err){});});- Read my Distributed locks using Redis article and Redis' author's A proposal for more reliable locks using Redis to learn more about the theory of distributed locks using Redis.