|
1234567891011121314151617181920212223242526272829303132333435363738394041424344 |
- namespace HealthMonitor.Core.Common
- {
- /// <summary>
- /// 分布式同步锁
- /// </summary>
- public class DistributedLocker : IDisposable
- {
- private const string KEY_LOCKER = nameof(DistributedLocker);
- private const int EXPIRE_SECONDS = 10;
-
- private CSRedis.CSRedisClientLock redis_lock;
-
- /// <summary>
- /// 分布式锁(基于Redis)
- /// </summary>
- /// <param name="caller"></param>
- /// <param name="isAutoDelay"></param>
- /// <exception cref="TimeoutException"></exception>
- public DistributedLocker(object caller, bool isAutoDelay = false) : this(caller.GetType().FullName, isAutoDelay) { }
-
- /// <summary>
- /// 分布式锁(基于Redis)
- /// </summary>
- /// <param name="title"></param>
- /// <param name="isAutoDelay"></param>
- /// <exception cref="TimeoutException"></exception>
- public DistributedLocker(string? title = null, bool isAutoDelay = false)
- {
- if (string.IsNullOrWhiteSpace(title)) title = KEY_LOCKER;
-
- redis_lock = RedisHelper.Lock(title, EXPIRE_SECONDS, isAutoDelay);
- if (redis_lock == null) throw new TimeoutException("RedisLock获取超时");
- }
-
-
-
- public void Dispose()
- {
- redis_lock?.Unlock();
-
- //RedisHelper.Del(KEY_LOCKER);
- }
- }
- }
|