A node.js semaphore implementation.
var traffic = require('node-traffic');
traffic.enter(function criticalZone () {
// ...
traffic.leave();
});
app.post('/resource', function (req, res) {
traffic.enter(function () {
// DB stuff...
traffic.leave();
res.respond();
});
});
traffic.enter('changeResource', function criticalZone () {
// ...
traffic.leave('changeResource');
});
app.post('/resource/:id', function (req, res) {
traffic.enter('changeResource-' + req.params.id, function () {
// DB stuff...
traffic.leave('changeResource-' + req.params.id);
res.respond();
});
});
Traffic allows to have a distributed semaphore across multiples nodes using Zookeeper.
var config = {
zkHost: 'localhost:2181', // host:port
zkRoot: '/', // znode path
zkTimeout: 4000 // 4 seconds
};
var traffic = require('node-traffic').distributed(config);
traffic.on('connectionTimeout', function (err) {
// handle Zookeeper connection timeout
});
zkRoot
will be created if it doesn't exists.
traffic.enter(function criticalZone () {
// ...
traffic.leave();
});
// Namespaced
traffic.enter('myNamespace', function () {
// ...
traffic.leave('myNamespace');
});
Note: Using namespaces creates znodes under config.zkRoot
.
Don't forget to close the Zookeeper connection...
process.on('exit',function(){
traffic.close();
});
If traffic
fails to connect to Zookeeper you can fallback into normal semaphores.
traffic.on('connectionTimeout', function (err) {
traffic = require('node-traffic');
});
Install jasmine
npm install -g jasmine
Run specs
npm test
jasmine spec/semaphore_spec.js
jasmine spec/distributed_semaphore_spec.js