|
| 1 | +import { Injectable, Logger, Scope } from '@nestjs/common'; |
| 2 | +import { RedisService } from '../../redis/redis.service'; |
| 3 | +import { randomBytes } from 'crypto'; |
| 4 | +import { hostname } from 'os'; |
| 5 | + |
| 6 | +@Injectable({ scope: Scope.DEFAULT }) |
| 7 | +export class LockerService { |
| 8 | + private readonly logger = new Logger(LockerService.name); |
| 9 | + private readonly LOCK_PREFIX = 'lock:'; |
| 10 | + private readonly DEFAULT_TTL = 30000; // 30秒默认超时 |
| 11 | + private readonly RETRY_DELAY = 1000; // 重试间隔 |
| 12 | + private readonly MAX_RETRY = 20; // 最大重试次数 |
| 13 | + private readonly id = `${process.pid}-${hostname()}-${randomBytes(16).toString('hex')}`; |
| 14 | + |
| 15 | + constructor(private readonly redisService: RedisService) {} |
| 16 | + |
| 17 | + async acquire(key: string, ttl: number = this.DEFAULT_TTL): Promise<boolean> { |
| 18 | + const lockKey = `${this.LOCK_PREFIX}${key}`; |
| 19 | + |
| 20 | + try { |
| 21 | + const result = await this.redisService.getRedis().set( |
| 22 | + lockKey, |
| 23 | + this.id, |
| 24 | + 'PX', |
| 25 | + ttl, |
| 26 | + 'NX' // Only set if key doesn't exist |
| 27 | + ); |
| 28 | + |
| 29 | + return result === 'OK'; |
| 30 | + } catch (error) { |
| 31 | + this.logger.error(`Failed to acquire lock for key ${key}: ${error.message}`); |
| 32 | + return false; |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + async release(key: string): Promise<boolean> { |
| 37 | + const lockKey = `${this.LOCK_PREFIX}${key}`; |
| 38 | + const luaScript = ` |
| 39 | + if redis.call("get", KEYS[1]) == ARGV[1] then |
| 40 | + return redis.call("del", KEYS[1]) |
| 41 | + else |
| 42 | + return 0 |
| 43 | + end |
| 44 | + `; |
| 45 | + |
| 46 | + try { |
| 47 | + const result = await this.redisService.getRedis().eval( |
| 48 | + luaScript, |
| 49 | + 1, |
| 50 | + lockKey, |
| 51 | + this.id |
| 52 | + ); |
| 53 | + |
| 54 | + return result === 1; |
| 55 | + } catch (error) { |
| 56 | + this.logger.error(`Failed to release lock for key ${key}: ${error.message}`); |
| 57 | + return false; |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + async extend(key: string, ttl: number): Promise<boolean> { |
| 62 | + const lockKey = `${this.LOCK_PREFIX}${key}`; |
| 63 | + |
| 64 | + const luaScript = ` |
| 65 | + if redis.call("get", KEYS[1]) == ARGV[1] then |
| 66 | + return redis.call("pexpire", KEYS[1], ARGV[2]) |
| 67 | + else |
| 68 | + return 0 |
| 69 | + end |
| 70 | + `; |
| 71 | + |
| 72 | + try { |
| 73 | + const result = await this.redisService.getRedis().eval( |
| 74 | + luaScript, |
| 75 | + 1, |
| 76 | + lockKey, |
| 77 | + this.id, // 使用固定的实例ID进行验证 |
| 78 | + ttl.toString() |
| 79 | + ); |
| 80 | + |
| 81 | + return result === 1; |
| 82 | + } catch (error) { |
| 83 | + this.logger.error(`Failed to extend lock for key ${key}: ${error.message}`); |
| 84 | + return false; |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + async isLocked(key: string): Promise<boolean> { |
| 89 | + const lockKey = `${this.LOCK_PREFIX}${key}`; |
| 90 | + const result = await this.redisService.getRedis().exists(lockKey); |
| 91 | + return result === 1; |
| 92 | + } |
| 93 | + |
| 94 | + async acquireWithRetry(key: string, ttl?: number, maxRetries: number = this.MAX_RETRY): Promise<boolean> { |
| 95 | + for (let i = 0; i < maxRetries; i++) { |
| 96 | + const acquired = await this.acquire(key, ttl); |
| 97 | + if (acquired) { |
| 98 | + return true |
| 99 | + }; |
| 100 | + |
| 101 | + // Wait before retrying |
| 102 | + await new Promise(resolve => setTimeout(resolve, this.RETRY_DELAY)); |
| 103 | + } |
| 104 | + return false; |
| 105 | + } |
| 106 | +} |
0 commit comments