Skip to content

Instantly share code, notes, and snippets.

@ejhari
Last active September 4, 2016 23:15
Show Gist options
  • Save ejhari/9afe3d9028583dcf781a60e4a7b970eb to your computer and use it in GitHub Desktop.
Save ejhari/9afe3d9028583dcf781a60e4a7b970eb to your computer and use it in GitHub Desktop.
Redis Distributed Lock Management
// REF: http://redis.io/topics/distlock
var redis = require('redis');
var Redlock = require('redlock');
var lock_client = redis.createClient(port, host, { db: 1 });
var lock_duration = 300000;, // in ms
var redlock = new Redlock(
// you should have one client for each redis node
// in your cluster
[lock_client],
{
// the expected clock drift; for more details
// see http://redis.io/topics/distlock
driftFactor: 0.01,
// the max number of times Redlock will attempt
// to lock a resource before erroring
retryCount: 3,
// the time in ms between attempts
retryDelay: 200
}
);
function acquireLock(resource, ttl, callback) {
redlock.lock(resource, ttl, function(err, lock) {
if (err) {
return callback(err, null);
}
var time_to_expire = 0;
lock.extend_timer = setInterval(function() {
time_to_expire = lock.expiration - Date.now();
logger.debug(S, 'Time to expire: %dms, for: %s', time_to_expire,
lock.resource);
lock.extend(ttl, function(err, lock) {
if (err) {
logger.error(S, 'Failed to extend for:', resource, err);
} else {
logger.debug(S, 'Extended for:', resource);
}
});
}, (time_to_expire + 0.85 * ttl));
return callback(null, lock);
});
}
function releaseLockSync(lock) {
clearInterval(lock.extend_timer);
lock.unlock();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment