Exclusion Mutuelle
Exclusion Mutuelle is a French language of Mutual Exclusion
. This is an implementation of mutex using redlock
and redis
.
Installation
npm install exclusion-mutuelle --save
Configuration
const mutex = ; const redisClients = ; const mutexConfig = redisClients // array of redis client to store the lock key debugKey: 'exclusion-mutuelle' // debug key to show debug message minimumTtl: 100 // minimum time to live when using mutex (in ms) extendLockBufferOffset: 50 // Interval for redlock to extend periodically (in ms) maxExtendLockCount: 20 // Maximum count that lock can be extended redlockOptions: retryCount: 0 // How many times to retry until the lock is acquired retryDelay: 1100 // Retry delay per attempt (in ms) // Please see https://github.com/mike-marcacci/node-redlock for details ; // mutexClient SHOULD be initiated as a singletonconst mutexClient = mutex;
Quick Usage
Running a function exclusively
...const mutexClient = mutex; // Function to print a message after x msconst printAfter = async { await Bluebird; console;}; const exclusiveFunc1 = ;const exclusiveFunc2 = ; // This function with lock key `lock-key` will run exclusively// Another function who use the same lock key, will not be able to run until this function finishedconst deferred1 = mutexClient; // This function will throw `LockError`, because the resource is still locked by `deferred1`// or you can make this function wait for `deferred1` if you set the `retryCount` and `retryDelay` in `redlockOptions`const deferred2 = mutexClient ; Bluebird alldeferred1 deferred2
Using multiple lock keys
You can set multiple lock key by passing an array of string to lockKey
parameter.
...const mutexClient = mutex; // Function to print a message after x msconst printAfter = async { await Bluebird; console;}; const exclusiveFunc1 = ;const exclusiveFunc2 = ; // The function with multiple lock key (`lock-key1`, `lock-key2`)// Another function who use these lock keys will not be able to run until this function finishedconst deferred1 = mutexClient; // This function will throw `LockError`, because `lock-key1` is still locked by `deferred1`const deferred2 = mutexClient; Bluebird alldeferred1 deferred2