redis-mutex
v2.0.1
Published
Mutex for distributed applications using redis.
Downloads
120
Readme
REDIS-MUTEX
Nodejs mutex implementation using the redis' set nx/xx/px
commands.
USAGE
var redis = require("redis");
var client = redis.createClient();
var redisMutex = require("redis-mutex");
var runWithMutex = redisMutex.runWithMutex;
runWithMutex({
intervalTime: 2000,
renewTime: 100,
maxTime: 10000,
key: "PROCESS_1",
redisClient: client
}, function(cb) {
// this is the code of our function
setTimeout(cb, 1000);
})
.then(function() {
return "OK";
}, function() {
return "REJECTED";
});
API
runWithMutex()
Arguments
| name | type | description | |-----------------|----------|------------------------------------------------------------------------------------------------------------| | inervalTime | number | The granularity at which the mutex updates itself in milliseconds. | | renewTime | number | How many ms before intervalTime a renew request is sent to redis. | | maxTime | number | The maximum time the function is allowed to run before it is killed. | | key | string | A string label of the mutex. Only one function with the same key is allowed to run. | | redisClient | object | Instance of redisClient from redis, providing the redis connection. | | fn | function | The actual processing function. |
Return value
The function returns a promise.
The promise is rejected when the mutex is locked or fn
calls the callback with an error.
The promise is resolved once fn
calls the callback without an error.
Error states
In case the redis record can't be updated the whole process is terminated since something had to go wrong. When the maxTime is exceeded the process is also terminated since there is no way in nodejs to terminate the function.