I've written an article http://www.cnblogs.com/axel10/p/8459434.html about C # operations Redis, The case in this article uses Stringincrement to achieve a steady increase in key values in high concurrency, but what if you want to use a lock instead of the Stringincrement method?
Locktake involves three parameters: Key,token and TimeSpan, respectively, representing the name of the lock in the Redis database, the bearer identity of the lock, and the valid time. Here's a case for adding a multi-threaded key value to demonstrate the use of locktake/lockrelease.
usingStackexchange.redis;usingStackExchange.Redis.Extensions.Core;usingStackExchange.Redis.Extensions.Core.Configuration;usingStackExchange.Redis.Extensions.Newtonsoft;usingSystem;usingSystem.Threading;namespaceredistest{classProgram {StaticRedisvalue Token =Environment.MachineName; StaticRediskey Key ="Lock"; Static voidIns () {thread thread=NewThread (() = { for(inti =0; I < -; i++) { if(Client. Database.locktake (Key, Token, TimeSpan.MaxValue))//key represents the name of the lock in the Redis database and cannot be duplicated. Token is used to identify who owns the lock and is used to release the lock. A timespan indicates the effective time of the lock. { Try { intKey = client. get<int> ("Key"); Client. ADD ("Key", Key +Ten); } Catch(Exception e) {Console.WriteLine (e); Throw; } finally{client. Database.lockrelease (Key, Token); } } Else{Console.WriteLine ("Locking"); while(! Tryagain (Ten) {thread.sleep (1); } } } }); Thread. Start (); } Private Staticstackexchangerediscacheclient Client; Static voidMain (string[] args) { varRedisconfiguration =NewRedisconfiguration ()//Configuration{Hosts=Newredishost[] {NewRedishost () {Host ="127.0.0.1", Port =6379} } }; Client=NewStackexchangerediscacheclient (NewNewtonsoftserializer (), redisconfiguration); Client. ADD ("Key",0); for(intj =0; J <Ten; J + +) {Ins (); } thread.sleep ( -); inti = client. get<int> ("Key"); Console.WriteLine (i); Console.readkey (); } Static BOOLTryagain (intvalue) { if(client. Database.locktake (Key, Token, TimeSpan.MaxValue)) {Try { intKey = client. get<int> ("Key"); Client. ADD ("Key", Key +value); } Catch(Exception e) {Console.WriteLine (e); Throw; } finally{client. Database.lockrelease (Key, Token); } return true; } Else { return false; } } }}
C # Redis uses locks (Stackexchange.redis Locktake) to ensure data correctness in high concurrency situations