Redis has three of the most basic properties to ensure effective implementation of distributed locks:
- Security: Mutex, at any time, only one client can hold a lock.
- Active A: There is no deadlock, even if the client crashes while holding the lock, there will be other clients to obtain the lock, timeout mechanism.
- Active B: Failure tolerance, only the majority of Redis nodes survive, the client can still get locks and release locks.
The use of Stackexchange.redis is easy to implement.
Static voidLock () {Console.WriteLine ("Start ... .."); vardb =_redis. Getdatabase (); Redisvalue token=Environment.MachineName; //actual item seconds kill here can be replaced by Product ID if(Db. Locktake ("Test", token, Timespan.fromseconds (Ten))) { Try{Console.WriteLine ("working ....."); Thread.Sleep ( the); } finally{db. Lockrelease ("Test", token); }} Console.WriteLine ("Over ... .."); }
Last attached github address: Https://github.com/xiaopotian1990/RedisDemo
C # uses Redis to implement distributed locks