Compare commits

..

No commits in common. "cfd430e31c2e5fabf439de2f5a26a45810c2d52e" and "bd5987fb4610649d6eaa209abb90ed7961cd7401" have entirely different histories.

3 changed files with 15 additions and 10 deletions

View File

@ -9,17 +9,17 @@ type RedisClient = redis.RedisClientType<
export class MutexLock { export class MutexLock {
redisClient: RedisClient; redisClient: RedisClient;
mutexOptions: MutexOptions | undefined; mutexOptions: MutexOptions;
constructor(redisClient: RedisClient, options?: MutexOptions) { constructor(redisClient: RedisClient, options: MutexOptions) {
this.mutexOptions = options; this.mutexOptions = options;
this.redisClient = redisClient; this.redisClient = redisClient;
} }
static async create(options?: MutexOptions) { static async create(options: MutexOptions) {
const redisClient = await redis const redisClient = await redis
.createClient({ .createClient({
url: `redis://${options?.redis?.host ?? "127.0.0.1"}:${options?.redis?.port ?? 6379}`, url: `redis://${options.redis.host}:${options.redis.port}`,
}) })
.connect(); .connect();
@ -40,12 +40,12 @@ export class MutexLock {
if (acquired) { if (acquired) {
await this.redisClient.expire( await this.redisClient.expire(
lockIdentifier, lockIdentifier,
this.mutexOptions?.mutex?.ttl || 60 this.mutexOptions.mutex?.ttl || 60
); );
return releaseFunc; return releaseFunc;
} }
await new Promise(resolve => await new Promise(resolve =>
setTimeout(resolve, this.mutexOptions?.mutex?.checkInterval || 100) setTimeout(resolve, this.mutexOptions.mutex?.checkInterval || 100)
); );
} }
}} }}

View File

@ -1,7 +1,7 @@
export type MutexOptions = { export type MutexOptions = {
redis?: { redis: {
host?: string; host: string;
port?: number; port: number;
}; };
mutex?: { mutex?: {
checkInterval?: number; checkInterval?: number;

View File

@ -4,7 +4,12 @@ import { MutexLock } from "../src/MutexLock";
test( test(
"redis mutex", "redis mutex",
async () => { async () => {
const mutexLock = await MutexLock.create(); const mutexLock = await MutexLock.create({
redis: {
host: "127.0.0.1",
port: 6379,
},
});
const testLock = async () => { const testLock = async () => {
const release = await mutexLock.obtainLock("test"); const release = await mutexLock.obtainLock("test");