At work, there are often problems with resource access conflicts in a distributed environment, such as a store's inventory number processing, or an atomic operation of an event, which requires ensuring that only one thread accesses or processes resources within a certain time period.
So now there are many distributed lock solutions on the Internet, such as database, MemCache, Zoopkeeper and so on.
This time, we are going to learn a Redis-based distributed lock plug-in, redlock.net.
There must first be a Redis service to support this distributed lock, and then of course it is to get the plugin.
You can get it from nuget or go directly to GitHub to download https://github.com/samcook/RedLock.net.
Get to the plug-in, words not much to say on the code. This is the encapsulation class for distributed locks, which can be called directly where a lock is required.
usingRedlock;usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Net;namespacekingsblog.core{ Public classDistributedlockmanager {PrivateList<redislockendpoint>Azureendpoint; PublicDistributedlockmanager () {Azureendpoint=NewList<redislockendpoint>(); Azureendpoint.addrange (Getendpoint (). Select (o=Newredislockendpoint {EndPoint = o.item1, Password =o.item2})); } /// <summary> ///To obtain a Redis connection from a configuration file/// </summary> /// <returns></returns> PrivateList<tuple<endpoint,string>>Getendpoint () {List<tuple<endpoint,string>> result =NewList<tuple<endpoint,string>>(); varRedisparms = RedisCacheBase.ConnectionString.Split (';'); //"127.0.0.1:6379,password=ucs123;127.0.0.1:6378,password=ucs123;" foreach(varReinchredisparms) { varRe1 = Re. Split (','); varRe2 = re1[0]. Split (':'); varRe3 = re1[0]. Split ('='); Result. ADD (NewTuple<endpoint,string> (NewDnsendpoint (re2[0], Convert.ToInt16 (Re2. Length >1? re2[1] :"6379")), re3[1])); } returnresult; } /// <summary> ///blocking calls, things will eventually be called (wait time)/// </summary> /// <param name= "resource" >Lock the identity of a resource</param> /// <param name= "Expirytime" >Lock Expiration Time</param> /// <param name= "WaitTime" >Wait Time</param> /// <param name= "work" ></param> Public BOOLBlockingwork (stringresource, TimeSpan Expirytime, TimeSpan WaitTime, Action work) {Resource=CreateKey (Resource); using(varRedislockfactory =Newredislockfactory (Azureendpoint)) { //blocks until acquired or ' wait ' timeout using(varRedislock = redislockfactory.create (Resource, Expirytime, WaitTime, Timespan.fromseconds (1))) { if(redislock.isacquired) {work (); return true; } } return false; } } /// <summary> ///skipping calls, if things are being called, skip directly over/// </summary> /// <param name= "resource" >Lock the identity of a resource</param> /// <param name= "Expirytime" >Lock Expiration Time</param> /// <param name= "work" ></param> Public BOOLOverlappingwork (stringresource, TimeSpan expirytime, Action work) {Resource=CreateKey (Resource); using(varRedislockfactory =Newredislockfactory (Azureendpoint)) { using(varRedislock =redislockfactory.create (Resource, expirytime)) { if(redislock.isacquired) {work (); return true; } } return false; } } /// <summary> ///Reset Key/// </summary> /// <param name= "key" ></param> /// <returns></returns> Private stringCreateKey (stringkey) { return string. Join ("_", Rediscachebase.systemcode,"LOCK", key); } }}
View Code
Call example, simple rough
Distributedlockmanager lockmanager=NewDistributedlockmanager (); TimeSpan Expirytime=NewTimeSpan (0,3,0); BOOLIswork=lockmanager.overlappingwork ("Lockname", Expirytime, () ={work ();//Do your job }); if(iswork) {//Successful Execution } Else { //not executed}
View Code
This makes it very simple to implement a Redis-based distributed lock.
Code is very simple, interested friends can also use the anti-compilation software Ilspy to understand the redlock implementation principle, the following two is actually redlock part of the source code:
Other will not say more, if in doubt, welcome to put forward.
Redlock.net-Open source implementation based on Redis distributed lock