|
using RedLock;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
namespace KingsBlog.Core
{
public>{private List<RedisLockEndPoint> azureEndPoint;public DistributedLockManager() {
azureEndPoint
= new List<RedisLockEndPoint>(); azureEndPoint.AddRange(GetEndPoint().Select(o
=> new RedisLockEndPoint { EndPoint = o.Item1, Password = o.Item2 })); }
/// <summary> /// 从配置文件获取Redis连接
/// </summary>
/// <returns></returns>
private List<Tuple<EndPoint, string>> GetEndPoint()
{
List<Tuple<EndPoint, string>> result = new List<Tuple<EndPoint, string>>();
var redisParms = RedisCacheBase.ConnectionString.Split(';');
// "127.0.0.1:6379,password=ucs123;127.0.0.1:6378,password=ucs123;"
foreach (var re in redisParms)
{
var re1 = re.Split(',');
var re2 = re1[0].Split(':');
var re3 = re1[0].Split('=');
result.Add(new Tuple<EndPoint, string>(new DnsEndPoint(re2[0], Convert.ToInt16(re2.Length > 1 ? re2[1] : "6379")), re3[1]));
}
return result;
}
/// <summary>
/// 阻塞式调用,事情最终会被调用(等待时间内)
/// </summary>
/// <param name="resource">锁定资源的标识</param>
/// <param name="expiryTime">锁过期时间</param>
/// <param name="waitTime">等待时间</param>
/// <param name="work"></param>
public bool BlockingWork(string resource, TimeSpan expiryTime, TimeSpan waitTime, Action work)
{
resource = CreateKey(resource);
using (var redisLockFactory = new RedisLockFactory(azureEndPoint))
{
// blocks until acquired or 'wait' timeout
using (var redisLock = redisLockFactory.Create(resource, expiryTime, waitTime, TimeSpan.FromSeconds(1)))
{
if (redisLock.IsAcquired)
{
work();
return true;
}
}
return false;
}
}
/// <summary>
/// 跳过式调用,如果事情正在被调用,直接跳过
/// </summary>
/// <param name="resource">锁定资源的标识</param>
/// <param name="expiryTime">锁过期时间</param>
/// <param name="work"></param>
public bool OverlappingWork(string resource, TimeSpan expiryTime, Action work)
{
resource = CreateKey(resource);
using (var redisLockFactory = new RedisLockFactory(azureEndPoint))
{
using (var redisLock = redisLockFactory.Create(resource, expiryTime))
{
if (redisLock.IsAcquired)
{
work();
return true;
}
}
return false;
}
}
/// <summary>
/// 重新设置键
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
private string CreateKey(string key)
{
return string.Join("_", RedisCacheBase.SystemCode, "LOCK", key);
}
}
} |
|
|