Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

DistributedLocker.cs 1.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. namespace HealthMonitor.Core.Common
  2. {
  3. /// <summary>
  4. /// 分布式同步锁
  5. /// </summary>
  6. public class DistributedLocker : IDisposable
  7. {
  8. private const string KEY_LOCKER = nameof(DistributedLocker);
  9. private const int EXPIRE_SECONDS = 10;
  10. private CSRedis.CSRedisClientLock redis_lock;
  11. /// <summary>
  12. /// 分布式锁(基于Redis)
  13. /// </summary>
  14. /// <param name="caller"></param>
  15. /// <param name="isAutoDelay"></param>
  16. /// <exception cref="TimeoutException"></exception>
  17. public DistributedLocker(object caller, bool isAutoDelay = false) : this(caller.GetType().FullName, isAutoDelay) { }
  18. /// <summary>
  19. /// 分布式锁(基于Redis)
  20. /// </summary>
  21. /// <param name="title"></param>
  22. /// <param name="isAutoDelay"></param>
  23. /// <exception cref="TimeoutException"></exception>
  24. public DistributedLocker(string? title = null, bool isAutoDelay = false)
  25. {
  26. if (string.IsNullOrWhiteSpace(title)) title = KEY_LOCKER;
  27. redis_lock = RedisHelper.Lock(title, EXPIRE_SECONDS, isAutoDelay);
  28. if (redis_lock == null) throw new TimeoutException("RedisLock获取超时");
  29. }
  30. public void Dispose()
  31. {
  32. redis_lock?.Unlock();
  33. //RedisHelper.Del(KEY_LOCKER);
  34. }
  35. }
  36. }