cloudLogList.lock.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import logger from '@/logger'
  2. import redis from './redis.lock'
  3. import RedisLock, { type Lock } from 'redlock'
  4. const redisLock = new RedisLock(
  5. // You should have one client for each independent redis node or cluster.
  6. [redis],
  7. {
  8. // The expected clock drift; for more details see:
  9. // http://redis.io/topics/distlock
  10. // 容忍的漂移因子
  11. driftFactor: 0.01, // multiplied by lock ttl to determine drift time
  12. // The max number of times Redlock will attempt to lock a resource before erroring.
  13. // 重试次数
  14. retryCount: 10,
  15. // the time in ms between attempts
  16. // 重试间隔
  17. retryDelay: 200, // time in ms
  18. // the max time in ms randomly added to retries to improve performance under high contention
  19. // see https://www.awsarchitectureblog.com/2015/03/backoff.html
  20. // 随机延迟
  21. retryJitter: 200, // time in ms
  22. // The minimum remaining time on a lock before an extension is automatically attempted with the `using` API.
  23. automaticExtensionThreshold: 500, // time in ms
  24. }
  25. )
  26. const lockKey = 'locks:cloud_log_list'
  27. const delay = 5 * 60 *1000 // ms
  28. let lock: Lock | undefined = undefined
  29. export async function listLock() {
  30. lock = await redisLock.acquire([...lockKey], delay);
  31. logger.info('cloud log list lock acquired!');
  32. }
  33. export async function extendLock() {
  34. lock = await lock?.extend(delay)
  35. logger.info('cloud log list lock extend!');
  36. }
  37. export async function listUnlock() {
  38. await lock?.release();
  39. logger.info('cloud log list lock released!');
  40. lock = undefined
  41. }
  42. // 检查资源是否已锁定
  43. export function checkLockStatus() {
  44. if (lock === undefined) {
  45. logger.info('cloud log resource is not locked.');
  46. return false; // 未被锁定
  47. } else {
  48. logger.info('cloud log resource is already locked.');
  49. return true; // 已被锁定
  50. }
  51. }