csrediscore實現分布式鎖 小計


參考文章: https://segmentfault.com/a/1190000018106844

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

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("127.0.0.1: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);
                    Thread.Sleep(2000);

                    //釋放鎖
                    Console.WriteLine("解鎖 : 我是" + k + " ,當前時間: " + DateTime.Now);
                    RedisLock.DelLock("LockKey");
                    return;
                }

                Console.WriteLine("其他人在用,我是: " + k + " ,count現在值:" + count + " ,當前時間: " + DateTime.Now);
                return;
            }
            finally
            {
                ////不能再finally解鎖, finally在return前執行 ,起不到鎖的作用
                //Console.WriteLine("解鎖 : 我是" + k + " ,當前時間: " + DateTime.Now);
                //RedisLock.DelLock("LockKey");
            }
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM