Last active
January 30, 2017 23:12
-
-
Save david-martin/777398a61f3f9967da5045bb2e9f3ffc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "redis-watch-test", | |
"version": "1.0.0", | |
"description": "", | |
"main": "index.js", | |
"scripts": { | |
"test": "echo \"Error: no test specified\" && exit 1" | |
}, | |
"author": "", | |
"license": "ISC", | |
"dependencies": { | |
"redis": "^2.6.5", | |
"redlock": "^2.1.0" | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var redis = require('redis'); | |
var Redlock = require('redlock'); | |
var resource = 'locks:datasetclient:myShoppingList'; | |
var ttl = 501; | |
var client1 = redis.createClient(); | |
var client2 = redis.createClient(); | |
var client3 = redis.createClient(); | |
console.log('create Redlock'); | |
var redlock1 = new Redlock( | |
// you should have one client for each redis node | |
// in your cluster | |
[client1], | |
{ | |
retryCount: 0 | |
} | |
); | |
var redlock2 = new Redlock( | |
// you should have one client for each redis node | |
// in your cluster | |
[client2], | |
{ | |
retryCount: 0 | |
} | |
); | |
var redlock3 = new Redlock( | |
// you should have one client for each redis node | |
// in your cluster | |
[client3], | |
{ | |
retryCount: 0 | |
} | |
); | |
function loop(redlock, id) { | |
console.log('get lock', id); | |
redlock.lock(resource, ttl).then(function(lock) { | |
console.log('got lock', id); | |
setTimeout(function() { | |
return loop(redlock, id); | |
}, 500); | |
}).catch(function(){ | |
console.log('err', id, arguments); | |
setTimeout(function() { | |
return loop(redlock, id); | |
}, 500); | |
}); | |
} | |
console.log('infinite recursive loops'); | |
setTimeout(function() { | |
loop(redlock1, 1); | |
}, 0); | |
setTimeout(function() { | |
loop(redlock2, 2); | |
}, 0); | |
setTimeout(function() { | |
loop(redlock3, 3); | |
}, 0); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ node test.js | grep "got lock" | |
got lock 1 | |
got lock 1 | |
got lock 2 | |
got lock 1 | |
got lock 3 | |
got lock 3 | |
got lock 1 | |
got lock 3 | |
got lock 1 | |
got lock 1 | |
got lock 3 | |
got lock 1 | |
got lock 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment