数据库
首页 > 数据库> > 如果利用Redis实现分布式锁

如果利用Redis实现分布式锁

作者:互联网

 

 

入口函数

class Program
    {
        static void Main(string[] args)
        {
            for (var i = 0; i < 10; i++)
            {
                Task.Run(() =>
                {
                    new TestService().Run();
                });
            }

            Console.ReadKey();
        }
    }

 

业务函数

public class TestService
    {
        private readonly RedisCacheService _cacheService;
        private readonly RedisLockService _lockService;

        public TestService()
        {
            _cacheService = new RedisCacheService(new RedisCacheOptions
            {
          //Redis连接字符串 Configuration = "xxx" }); _lockService = new RedisLockService(); } public void Run() { //创建锁 _lockService.Create("test"); //设置数量 SetCount(); //显示数量 ShowCount(); //释放锁 _lockService.Clear("test"); } public void SetCount() { _cacheService.Set("count", _cacheService.Get<int>("count") + 1); } public void ShowCount() { Console.WriteLine(_cacheService.Get<int>("count")); } }

 

锁函数

public class RedisLockService
    {
        private readonly RedisCacheService _cacheService;

        public RedisLockService()
        {
            _cacheService = new RedisCacheService(new RedisCacheOptions
            {
                Configuration = "cleidon-iot-test.redis.cache.chinacloudapi.cn:6380,password=55SdeLifKGFAY1QJ0HRIlhbHqUKkOb8y2a4IGkYtot0=,ssl=True,abortConnect=False"
            });
        }

        /// <summary>
        /// 创建锁
        /// </summary>
        /// <param name="name">锁名</param>
        public void Create(string name)
        {
            //锁标识,证明是当前程序创建的锁
            var flag = CommonUtil.NewGuid();

            while (!Get(name, flag)) //锁验证,若未获取到自己创建的锁,则进入循环,反之跳出循环执行后续代码
            {
                //锁检测,若发现锁已被占用,则进入循环等待50ms,反之跳出循环执行后续代码
                while (Check(name))
                {
                    Thread.Sleep(50);
                }

                //锁设置,设置属于自己的锁,由于存在并发问题,锁有可能被其他程序覆盖,因此才需要循环进行锁验证
                Set(name, flag);
            }

        }

        /// <summary>
        /// 释放锁
        /// </summary>
        /// <param name="name">锁名</param>
        public void Clear(string name)
        {
            _cacheService.Remove($"lock-{name}");
        }
        private bool Check(string name)
        {
            return _cacheService.IsExist($"lock-{name}");
        }

        private bool Get(string name, string flag)
        {
            return _cacheService.Get<string>($"lock-{name}") == flag;
        }

        private void Set(string name, string flag)
        {
            _cacheService.Set($"lock-{name}", flag, 100);
        }
    }

 

标签:name,cacheService,void,Redis,利用,flag,public,string,分布式
来源: https://www.cnblogs.com/rhyheart/p/15246605.html