swarthy / redis-semaphore

Distributed mutex and semaphore based on Redis
MIT License
148 stars 28 forks source link

redis cluster is not supported for Semaphore #186

Closed xiaoke314 closed 6 months ago

xiaoke314 commented 1 year ago

My codes:

const {Semaphore, TimeoutError} = require('redis-semaphore'); const Redis = require('ioredis');

redis = new Redis.Cluster( [ { host: REDIS_HOST, port: 6379 } ], { slotsRefreshTimeout: 10000, redisOptions: { password: REDIS_TOKEN, tls: false } } )

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

When running new Semaphore(redis, 'lockingResource', 5), the following error throwed:

Error: "client" must be instance of ioredis client or cluster at new RedisMutex (C:\workspace\node-test\node_modules\redis-semaphore\lib\RedisMutex.js:19:19) at new RedisSemaphore (C:\workspace\node-test\node_modules\redis-semaphore\lib\RedisSemaphore.js:12:9)

swarthy commented 1 year ago

Hi. Error message is invalid, don't use cluster directly in Mutex constructor, see redlock example.

xiaoke314 commented 1 year ago

Thank you for your help. I have tried the RedlockSemaphore, but it always fail with TimeoutError when acquire.

I use the following codes to construct RedlockSemaphore

const options = { "lockTimeout": 30000, "acquireTimeout": 10000, "acquireAttemptsLimit": Number.POSITIVE_INFINITY, "retryInterval": 10, "refreshInterval": 30000 * 0.8 }; const redisClients = redis.nodes("master"); const semaphore = new RedlockSemaphore(redisClients, semaphoreKey, 5, options); await semaphore.acquire();

The error: TimeoutError: Acquire redlock-semaphore semaphore:34ca2e78-d55d-4b4d-9ffb-dd8aec7dc5d0 timeout at RedlockSemaphore.acquire (C:\workspace\cvdt-azure-functions\node_modules\redis-semaphore\lib\Lock.js:100:19) at async executeWithSemaphoreAndCancelCheck (C:\workspace\cvdt-azure-functions\common\dataCache.js:193:9) at async module.exports (C:\workspace\cvdt-azure-functions\api-trip-queuedquery\index.js:17:22)

swarthy commented 6 months ago

There are tests for redlock semaphore https://github.com/swarthy/redis-semaphore/blob/master/test/src/RedlockSemaphore.test.ts. Case similar to yours is covered, check infrastructure (network). Or please add PR with failing test with redlock semaphore.