import { range } from "lodash";
import Redis from "ioredis";
import Redlock from "redlock";
import { RedisOptions } from "ioredis";
///const redis = new Redis(6379, "192.168.116.130", { password: "123456" });
export class RedLockRedis {
private client: Redis;
private redLock: Redlock;
private mutexLock: any;
private lockName = "variables:lock";
constructor(port: number, host: string, option: RedisOptions) {
this.client = new Redis(port, host, option);
this.redLock = new Redlock([this.client], {
driftFactor: 0.01, // multiplied by lock ttl to determine drift time
retryCount: 20,
retryDelay: 2000, // time in ms
retryJitter: 200, // time in ms
automaticExtensionThreshold: 500, // time in ms
});
}
public get Client() {
return this.client;
}
public Connect() {
this.client.connect();
}
public DisConnect() {
this.client.disconnect();
}
public async Lock() {
this.mutexLock = await this.redLock.acquire([this.lockName], 5000);
}
public async UnLock() {
await this.mutexLock.release();
}
public async HSet(key: string, field: string, value: any) {
await this.client.hset(key, field, JSON.stringify(value));
}
public async HGet(key: string, field: string) {
const value = await this.client.hget(key, field);
return JSON.parse(value ?? '""');
}
}
(async () => {
const redisLock = new RedLockRedis(6379, "192.168.116.130", { password: "123456" });
for (const v of range(1, 10001)) {
await redisLock.Lock();
let value = await redisLock.HGet("global", "name");
if (value) {
console.log("value=", ++value);
await redisLock.HSet("global", "name", value);
} else {
console.log("value=", 1);
await redisLock.HSet("global", "name", 1);
}
await redisLock.UnLock();
}
})();
09-06
896
