Skip to content
Distributed mutex and semaphore based on Redis
Branch: master
Clone or download
Pull request Compare This branch is 4 commits ahead, 62 commits behind swarthy:master.
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
lib
test
.codeclimate.yml
.eslintignore init Jan 12, 2018
.eslintrc mutex alpha Jan 13, 2018
.gitignore
.travis.yml init Jan 12, 2018
LICENSE
README.md
index.js
package.json
yarn.lock

README.md

redis-semaphore

NPM version Build status Dependency Status Coverage Status Code Climate Known Vulnerabilities

Mutex and Semaphore implementations based on Redis ready for distributed systems

Features

  • Fail-safe (all actions performed by LUA scripts (atomic))

Usage

Mutex

new Mutex(redisClient, key [, { lockTimeout = 10000, acquireTimeout = 10000, retryInterval = 10, refreshInterval = acquireTimeout * 0.8 }])
  • redisClient - required, configured redis client
  • key - required, key for locking resource (final key in redis: mutex:<key>)
  • timeouts optional
    • lockTimeout - ms, time after mutex will be auto released (expired)
    • acquireTimeout - ms, max timeout for .acquire() call
    • retryInterval - ms, time between acquire attempts if resource locked
    • refreshInterval - ms, auto-refresh interval

Example

const Mutex = require('redis-semaphore').Mutex
const redis = require('redis')

const redisClient = redis.createClient()

async function doSomething() {
  const mutex = new Mutex(redisClient, 'lockingResource')
  await mutex.acquire()
  // critical code
  await mutex.release()
}

Semaphore

new Semaphore(redisClient, key, maxCount [, { lockTimeout = 10000, acquireTimeout = 10000, retryInterval = 10, refreshInterval = acquireTimeout * 0.8 }])
  • redisClient - required, configured redis client
  • key - required, key for locking resource (final key in redis: semaphore:<key>)
  • maxCount - required, maximum simultaneously resource usage count
  • timeouts optional
    • lockTimeout - ms, time after semaphore will be auto released (expired)
    • acquireTimeout - ms, max timeout for .acquire() call
    • retryInterval - ms, time between acquire attempts if resource locked
    • refreshInterval - ms, auto-refresh interval

Example

const Semaphore = require('redis-semaphore').Semaphore
const redis = require('redis')

const redisClient = redis.createClient()

async function doSomething() {
  const semaphore = new Semaphore(redisClient, 'lockingResource', 5)
  await semaphore.acquire()
  // maximum 5 simultaneously executions
  await semaphore.release()
}

Installation

npm install --save redis-semaphore
# or
yarn add redis-semaphore

License

MIT

You can’t perform that action at this time.