Skip to content

Instantly share code, notes, and snippets.

@chilts
Last active December 17, 2015 09:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chilts/5588824 to your computer and use it in GitHub Desktop.
Save chilts/5588824 to your computer and use it in GitHub Desktop.
Lock API using Redis
var redis = require('redis');
var redlock = require('redlock');
var getLock2 = redlock({
client : client,
prefix : 'lock:', // optional
});
var getLock2 = redlock({
// same credentials as redis.createClient()
});
// simple example
getLock1('alock', function(err, lock) {
// if there's been a bad error, get out of here
if (err) throw err;
// if we didn't get the lock, just return
if ( !lock ) return;
doSomethingInvolvingAsync(function(err) {
// we've now finished with the lock
lock.release();
});
});
// more complete example, hold lock for 2 mins
console.log('Trying to get mylock');
getLock2('mylock', 120, function(err, lock) {
// if something went badly wrong, we need to do something
if (err) throw err;
if ( lock ) {
// yes, we got the lock, so do something and then call done
doSomething();
// if something takes a while, tell the lock you're still alive
lock.ping(function(err) {
// You don't need to listen for when the lock has been
// kept alive, but you could do if you want to log it.
console.log('Lock has been pinged');
});
return lock.release(function(err) {
// You don't need to listen for when the lock has been released
// but you could do, if you just want to log it or something.
console.log('Lock has been released');
});
}
// not got the lock ... from here we can retry or just quit
console.log("Didn't get lock");
});
@objectiveSee
Copy link

What module are you using for redlock? I can't find it in npm. Care you chime in about it here: redis/node-redis#687

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment