Battle-hardened distributed locking using redis.
- node-redis compatible with
=> v2.0.0 - Redis
v2.6.12or above.
npm install node-redis-warlock
varWarlock=require('node-redis-warlock');varredis=require('redis');// Establish a redis client and pass it to warlockvarredis=redis.createClient();varwarlock=Warlock(redis);// Set a lockvarkey='test-lock';varttl=10000;// Lifetime of the lockwarlock.lock(key,ttl,function(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 optimisticallyvarkey='opt-lock';varttl=10000;varmaxAttempts=4;// Max number of times to try setting the lock before erroringvarwait=1000;// Time to wait before another attempt if lock already in placewarlock.optimistic(key,ttl,maxAttempts,wait,function(err,unlock){});// unlock using the lock idvarkey='test-lock-2';varttl=10000;varlockId;warlock.lock(key,ttl,function(err,_,id){lockId=id;});// each client who knows the lockId can release the lockwarlock.unlock(key,lockId,function(err,result){if(result==1){// unlocked successfully}});- 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.