csrediscore實現分佈式鎖 小計

參考文章: http://www.javashuo.com/article/p-qjxajhkh-kz.htmlredis

項目使用的csrediscore, 下面是鎖定/解鎖2個方法segmentfault

using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace ConsoleApp1 { public static class RedisLock { /// <summary>
        /// 分佈式鎖 /// </summary>
        /// <param name="key">鎖key</param>
        /// <param name="lockExpirySeconds">鎖自動超時時間(秒)</param>
        /// <param name="waitLockMs">等待鎖時間(秒)</param>
        /// <returns></returns>
        public static bool Lock(string key, int lockExpirySeconds = 10, double waitLockSeconds = 0) { //間隔等待50毫秒
            int waitIntervalMs = 50; string lockKey = "LockForSetNX:" + key; DateTime begin = DateTime.Now; while (true) { //循環獲取取鎖
                if (RedisHelper.SetNx(lockKey, 1)) { //設置鎖的過時時間
 RedisHelper.Expire(lockKey, lockExpirySeconds); return true; } //不等待鎖則返回
                if (waitLockSeconds == 0) break; //超過等待時間,則再也不等待
                if ((DateTime.Now - begin).TotalSeconds >= waitLockSeconds) break; Thread.Sleep(waitIntervalMs); } return false; } /// <summary>
        /// 刪除鎖 執行完代碼之後調用釋放鎖 /// </summary>
        /// <param name="key"></param>
        public static void DelLock(string key) { string lockKey = "LockForSetNX:" + key; RedisHelper.Del(lockKey); } } }

 

程序中使用分佈式

using System; using System.Threading; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { private static int count = 0; static void Main(string[] args) { var csredis = new CSRedis.CSRedisClient("192.168.123.72:6379,defaultDatabase=1,syncTimeout=3000,WriteBuffer=102400"); //初始化 RedisHelper
 RedisHelper.Initialization(csredis); for (int i = 0; i < 100; i++) { var k = i; Task.Run(() => { add(k); }); Thread.Sleep(500); } Console.WriteLine("count=" + count); Console.ReadLine(); } static void add(int k) { try { //取鎖,設置key10秒後失效,最大等待鎖5秒
                if (RedisLock.Lock("LockKey", 5, 2)) { //取到鎖,執行具體業務
                    count++; Console.WriteLine("我拿到鎖了++++++++,我是: " + k + " ,count如今值:" + count + " ,當前時間: " + DateTime.Now); return; } Console.WriteLine("其餘人在用,我是: " + k + " ,count如今值:" + count + " ,當前時間: " + DateTime.Now); return; } finally { //釋放鎖 //RedisLock.DelLock("LockKey");
 } } } }
相關文章
相關標籤/搜索