Commit 932273f2 authored by nanahira's avatar nanahira

support stacked lock

parent 00e990df
......@@ -3,7 +3,7 @@ import { Settings } from '@nanahira/redlock';
export type RedisDriverOptions = RedisOptions & {
uri?: string;
lock?: Settings & { duration?: number; prefix?: string };
lock?: Settings & { duration?: number; prefix?: string; stacked?: boolean };
queueKey?: string;
};
......
......@@ -3,6 +3,7 @@ import Redis from 'ioredis';
import Redlock from '@nanahira/redlock';
import { Awaitable, RedisDriverOptions } from '../def';
import { createPool } from 'generic-pool';
import BetterLock from 'better-lock';
export class RedisDriver extends BaseDriver {
async createRedisClient() {
......@@ -94,15 +95,23 @@ export class RedisDriver extends BaseDriver {
await this.pool.use((r) => r.redis.del(keys));
}
private betterLock = new BetterLock();
override async lock<R>(keys: string[], cb: () => Promise<R>): Promise<R> {
return this.useTempRedisClient(async (redis) => {
const redlock = new Redlock([redis], this.options.lock);
return redlock.using(
keys.map((key) => `${this.options.lock?.prefix || '_lock'}:${key}`),
this.options.lock?.duration || 5000,
cb,
);
});
const run = () =>
this.useTempRedisClient(async (redis) => {
const redlock = new Redlock([redis], this.options.lock);
return redlock.using(
keys.map((key) => `${this.options.lock?.prefix || '_lock'}:${key}`),
this.options.lock?.duration || 5000,
cb,
);
});
if (this.options?.lock?.stacked) {
return this.betterLock.acquire(keys, run);
} else {
return run();
}
}
override async isFree(keys: string[]): Promise<boolean> {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment