0
点赞
收藏
分享

微信扫一扫

.net framework 4.5.1 , 基于redis的一个分布式锁简单示例,亲测


引用的版本如下:

.net framework 4.5.1 , 基于redis的一个分布式锁简单示例,亲测_.net4.5 redlock


主要是因为.net framework版本的限制。

我并没有安装下面的那个RedLock.net.Strongname,事实证明不需要。

直接上示例代码:


#define TEST1
using System;
using System.Collections.Generic;
using System.Net;
using RedLockNet.SERedis;
using RedLockNet.SERedis.Configuration;

namespace ConsoleApp2
{


public class Class1
{

public bool test1()
{

RedLockFactory redlockFactory = null;

#region 第一种

#if TEST1
var endPoints = new DnsEndPoint("1.1.1.1", 6379);
RedLockEndPoint point = new RedLockEndPoint(endPoints);
point.Password = "123456";
List<RedLockEndPoint> endpoints = new List<RedLockEndPoint>() { point };

redlockFactory = RedLockFactory.Create(endpoints);
#endif

#endregion



#region 第二种

#if TEST2
ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("1.1.1.1:6379,password=123456");
var multiplexers = new List<RedLockMultiplexer>
{
redis
};
redlockFactory = RedLockFactory.Create(multiplexers);

#endif
#endregion



var resource = "order-payment-callback-dist-lock";
var expiry = TimeSpan.FromSeconds(30);

using (var redLock = redlockFactory.CreateLock(resource, expiry))
{
//This is almost always false and the lock status is NoQuorum
if (redLock.IsAcquired)
{
//do what the fuck you want
}

}

return true;
}
}
}

亲测成功。

特别注意,把断点打在 ​​if (redLock.IsAcquired)​​​这一行上。
然后开始执行。
此时 ​​​redLock.IsAcquired​​​为​​true​​​。
不要跳过断点,此时打开redis客户端,可以看到新增的redis 的kv值。
然后跳过断点,则kv值消失(客户端需要刷新一下才能看到吧?)。
或者就不要用​​​using(xxxx)​​的写法,则redis中的kv值到了过期时间后会自动消失。


举报

相关推荐

0 条评论