var client1 = require('redis').createClient(6379, 'redis1.example.com'); var client2 = require('redis').createClient(6379, 'redis2.example.com'); var client3 = require('redis').createClient(6379, 'redis3.example.com'); var Redlock = require('redlock'); var redlock = new Redlock( // you should have one client for each independent redis node // or cluster [client1, client2, client3], { // the expected clock drift; for more details // see http://redis.io/topics/distlock driftFactor: 0.01, // time in ms // the max number of times Redlock will attempt // to lock a resource before erroring retryCount: 10, // the time in ms between attempts retryDelay: 200, // time in ms // the max time in ms randomly added to retries // to improve performance under high contention // see https://www.awsarchitectureblog.com/2015/03/backoff.html retryJitter: 200 // time in ms } );
Error Handling
1 2 3
redlock.on('clientError', function(err) { console.error('A redis error has occurred:', err); });
// the string identifier for the resource you want to lock var resource = 'locks:account:322456'; // the maximum amount of time you want the resource locked, // keeping in mind that you can extend the lock up until // the point when it expires var ttl = 1000; redlock.lock(resource, ttl).then(function(lock) { // ...do something here... // unlock your resource when you are done return lock.unlock() .catch(function(err) { // we weren't able to reach redis; your lock will eventually // expire, but you probably want to log this error console.error(err); }); });
// the string identifier for the resource you want to lock var resource = 'locks:account:322456';
// the maximum amount of time you want the resource locked, // keeping in mind that you can extend the lock up until // the point when it expires var ttl = 1000; redlock.lock(resource, ttl, function(err, lock) { // we failed to lock the resource if(err) { // ... } // we have the lock else { // ...do something here... // unlock your resource when you are done lock.unlock(function(err) { // we weren't able to reach redis; your lock will eventually // expire, but you probably want to log this error console.error(err); }); } });