Compare commits
4 Commits
bd5987fb46
...
cfd430e31c
Author | SHA1 | Date | |
---|---|---|---|
cfd430e31c | |||
20496cc24b | |||
33a49cba4a | |||
f65ab42231 |
@ -9,17 +9,17 @@ type RedisClient = redis.RedisClientType<
|
||||
|
||||
export class MutexLock {
|
||||
redisClient: RedisClient;
|
||||
mutexOptions: MutexOptions;
|
||||
mutexOptions: MutexOptions | undefined;
|
||||
|
||||
constructor(redisClient: RedisClient, options: MutexOptions) {
|
||||
constructor(redisClient: RedisClient, options?: MutexOptions) {
|
||||
this.mutexOptions = options;
|
||||
this.redisClient = redisClient;
|
||||
}
|
||||
|
||||
static async create(options: MutexOptions) {
|
||||
static async create(options?: MutexOptions) {
|
||||
const redisClient = await redis
|
||||
.createClient({
|
||||
url: `redis://${options.redis.host}:${options.redis.port}`,
|
||||
url: `redis://${options?.redis?.host ?? "127.0.0.1"}:${options?.redis?.port ?? 6379}`,
|
||||
})
|
||||
.connect();
|
||||
|
||||
@ -40,12 +40,12 @@ export class MutexLock {
|
||||
if (acquired) {
|
||||
await this.redisClient.expire(
|
||||
lockIdentifier,
|
||||
this.mutexOptions.mutex?.ttl || 60
|
||||
this.mutexOptions?.mutex?.ttl || 60
|
||||
);
|
||||
return releaseFunc;
|
||||
}
|
||||
await new Promise(resolve =>
|
||||
setTimeout(resolve, this.mutexOptions.mutex?.checkInterval || 100)
|
||||
setTimeout(resolve, this.mutexOptions?.mutex?.checkInterval || 100)
|
||||
);
|
||||
}
|
||||
}}
|
||||
|
@ -1,7 +1,7 @@
|
||||
export type MutexOptions = {
|
||||
redis: {
|
||||
host: string;
|
||||
port: number;
|
||||
redis?: {
|
||||
host?: string;
|
||||
port?: number;
|
||||
};
|
||||
mutex?: {
|
||||
checkInterval?: number;
|
||||
|
@ -4,12 +4,7 @@ import { MutexLock } from "../src/MutexLock";
|
||||
test(
|
||||
"redis mutex",
|
||||
async () => {
|
||||
const mutexLock = await MutexLock.create({
|
||||
redis: {
|
||||
host: "127.0.0.1",
|
||||
port: 6379,
|
||||
},
|
||||
});
|
||||
const mutexLock = await MutexLock.create();
|
||||
|
||||
const testLock = async () => {
|
||||
const release = await mutexLock.obtainLock("test");
|
||||
|
Loading…
x
Reference in New Issue
Block a user