Redis as a distributed lock

Redis as distributed lock service logic used

。。。

。。。

Simply use the case are as follows (commodity spike scenarios):

The following scenarios premise commodity spike case demonstrates that Redis is already installed, and can be used, the specific installation tutorial can refer to this article on the article  Redis Overview and Installation 

1, using Visual studio 2019 Enterprise to create a console project ConsoleTestRedis, select the right item, click NuGet package manager, search for and add StackExchange.Redis

2, add a client Client request class, commodity spike ProductKill, Redis class distributed lock RedisLock

Client Client request class code as follows:

using System.Threading;

namespace ConsoleTestRedis
{
    /// <summary>
    /// 客户端请求
    /// </summary>
    public class Client
    {
        public void CleitRequest()
        {
            ProductKill productKill = new ProductKill();

            for (int i = 0; i < 20; i++)
            {
                new Thread(() => { productKill.KillProduct(); }).Start();
            }
        }

    }
}

ProductKill spike commodity code is as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleTestRedis
{
    /// <summary>
    /// 商品秒杀
    /// </summary>
    public class ProductKill
    {
        /// <summary>
        /// 库存数量
        /// </summary>
        public int repositoryNumber = 10;

        /// <summary>
        /// 获取库存的数量
        ///  </ Summary> 
        ///  <Returns> </ Returns> 
        public  int GetRepositoryNumber () 
        { 
            return repositoryNumber; 
        } 

        ///  <Summary> 
        /// deducted Stock Number
         ///  </ Summary> 
        public  void SetRepositoryNumber () 
        { 
            repositoryNumber - ;; 
        } 

        ///  <Summary> 
        /// goods spike
         ///  </ Summary> 
        public  void KillProduct () 
        { 
            // using the distributed lock RedisLock Redis
            RedisLock = RedisLock new new RedisLock (); 
            redisLock.Lock (); 
            var restory = GetRepositoryNumber ();
             IF (restory == 0 ) 
            { 
                Console.WriteLine ($ " {} Sorry acquisition failure Thread.CurrentThread.ManagedThreadId stock quantity of a commodity! : repositoryNumber {} " ); 
                redisLock.UnLock (); 
                return ; 
            } 
            Console.WriteLine ($ " Congratulations {Thread.CurrentThread.ManagedThreadId} get spike commodity successful quantity stock:! repositoryNumber {} " ); 
        } 
            SetRepositoryNumber ();
            redisLock.UnLock (); 
    } 
}

 

Redis distributed lock RedisLock class code as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using StackExchange.Redis;

namespace ConsoleTestRedis
{
    /// <summary>
    /// Redis分布式锁
    /// </summary>
    public class RedisLock
    {
        /// <summary>
        /// redis分布式连接管理器
        /// </summary>
        public ConnectionMultiplexer _connectionMultiplexer { get; SET ;}
         ///  <Summary> 
        /// database
         ///  </ Summary> 
        public the IDatabase _database { GET ; SET ;} 

        public RedisLock () 
        { 
            // Redis API using a premise, the installation redis 2, NuGet package management add StackExchange.Redis 
            _connectionMultiplexer = ConnectionMultiplexer.Connect ( " localhost: 6379 " ); 
            _database = _connectionMultiplexer.GetDatabase ( 0 ); 
        } 

        ///  <Summary> 
        /// lock
         ///  </ Summary> 
        public void Lock () 
        { 
            the while ( to true ) 
            { 
                // LockTake Parameters (lockname, resulting acquired object expiration time) 
                BOOL isLocked = _database.LockTake ( " redis_key " , Thread.CurrentThread.ManagedThreadId, TimeSpan.FromSeconds ( 200 is )) ;
                 IF (isLocked) 
                { 
                    BREAK ; 
                } 
                the Thread.Sleep ( 200 is ); 
            } 
        } 

        ///  <Summary> 
        /// released
         ///  </ Summary> 
        public  voidUnLock () 
        { 
            // LockRelease Parameters (lockname obtain the resulting objects) 
            _database.LockRelease ( " redis_key " , Thread.CurrentThread.ManagedThreadId); 
            _connectionMultiplexer.Close (); 
        } 
    } 
}

 

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleTestRedis
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("。。。。。商品秒杀开始。。。。。。");
            Client client = new Client();
            client.CleitRequest();
            Console.ReadKey();
        }
    }
}

 

Operating results are as follows:

 

Guess you like

Origin www.cnblogs.com/1175429393wljblog/p/12310417.html