C#简单使用redis锁

使用redis命令

利用SETNX 来创建锁

 获取和删除SETNX

 //servcestack.redis3.9.7
public class RedisHelper
    {
        private readonly static string RedisPath = "[email protected]:6379";
        private readonly static PooledRedisClientManager _pool = null;
        public static IRedisClient redisClient = null;
        static RedisHelper()
        {
            if (redisClient == null)
            {
                _pool = new PooledRedisClientManager(new string[] { RedisPath }, 
new string[] { RedisPath }, 
new RedisClientManagerConfig() { MaxReadPoolSize = 50, 
                                MaxWritePoolSize = 50, 
                                    AutoStart = true });
            }
        }


 public static bool GetSetNX(string key) {
            bool issuccess = false;
            lock (_pool)
            {

                using (IRedisClient redisclient = _pool.GetClient())
                {
                    TimeSpan value = new TimeSpan(365, 0, 0, 0);
                    DateTime dateTime = DateTime.UtcNow.Add(value);
                    string value2 = (dateTime.ToUnixTimeMs() + 1L).ToString();
                    issuccess=redisclient.SetEntryIfNotExists(key, value2);
                }
            }
            return issuccess;
        }
        public static bool Remove(string key)
        {
            bool issuccess = false;
            lock (_pool)
            {

                using (IRedisClient redisclient = _pool.GetClient())
                {
                    issuccess = redisclient.Remove(key);
                }
            }
            return issuccess;
        }
         /// 
        /// 模拟使用
        /// 
        /// 
        public static bool SecKill2()
        {
            bool issuccess = false;
            using (IRedisClient r = _pool.GetClient())
            {
                using (RedisLock l=new RedisLock("lock"))
                {
                    try
                    {
                       //业务逻辑
                    }
                    catch (Exception ex)
                    {
                        l.Dispose();
                    }
                    finally
                    {

                    }
                }
            }
            return issuccess;
        }
}

 创建一个简单的锁

    public class RedisLock : IDisposable
    {
        private readonly string key;
        public void Dispose()
        {
            RedisHelper.Remove(key);
        }

        public  RedisLock(string _key) {
            this.key = _key;
            while (true) {
                if (RedisHelper.GetSetNX(key)) {
                    break ;
                }
                Thread.Sleep(100);
            }
        }
    }

 

 

你可能感兴趣的:(C#简单使用redis锁)