Redis教程

如果利用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);
        }
    }

 

这篇关于如果利用Redis实现分布式锁的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!