redis分布式锁使用方法

Posted lizhenhong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了redis分布式锁使用方法相关的知识,希望对你有一定的参考价值。

引用:

StackExchange.Redis.dll

Redlock.CSharp.dll

RedLock.dll

 

代码:

  public class RedlockHelper
    
        public void Lock(Action<bool> action, string val, string key = "PersonNo")
        
            Redlock.CSharp.Redlock dlm = new Redlock.CSharp.Redlock(RedisConnectionHelp.Instance);
            Lock lockObject;
            string resourceName = string.Format("Redlock_0_1", key, val);
            var locked = dlm.Lock(resourceName, new TimeSpan(0, 0, 10), out lockObject);
            try
            
                action.Invoke(locked);
            
            finally
            
                if (lockObject != null)
                    dlm.Unlock(lockObject);
            

        
    
 /// <summary>
    /// ConnectionMultiplexer对象管理帮助类
    /// </summary>
    public static class RedisConnectionHelp
    
        //系统自定义Key前缀
        public static readonly string SysCustomKey = ConfigurationManager.AppSettings["redisKey"] ?? ""; //从Redis获取AppSettings???

        //"127.0.0.1:6379,allowadmin=true
        private static readonly string RedisConnectionString = ConfigurationManager.ConnectionStrings["RedisExchangeHosts"].ConnectionString;

        private static readonly object Locker = new object();
        private static ConnectionMultiplexer _instance;
        private static readonly ConcurrentDictionary<string, ConnectionMultiplexer> ConnectionCache = new ConcurrentDictionary<string, ConnectionMultiplexer>();

        /// <summary>
        /// 单例获取
        /// </summary>
        public static ConnectionMultiplexer Instance
        
            get
            
                if (_instance == null)
                
                    lock (Locker)
                    
                        if (_instance == null || !_instance.IsConnected)
                        
                            _instance = GetManager();
                        
                    
                
                return _instance;
            
        

        /// <summary>
        /// 缓存获取
        /// </summary>
        /// <param name="connectionString"></param>
        /// <returns></returns>
        public static ConnectionMultiplexer GetConnectionMultiplexer(string connectionString)
        
            if (!ConnectionCache.ContainsKey(connectionString))
            
                ConnectionCache[connectionString] = GetManager(connectionString);
            
            return ConnectionCache[connectionString];
        

        private static ConnectionMultiplexer GetManager(string connectionString = null)
        
            connectionString = connectionString ?? RedisConnectionString;
            ConnectionMultiplexer connect;
            try
            
                connect = ConnectionMultiplexer.Connect(connectionString);
            
            catch
            
                return null;
            
            //注册如下事件
            connect.ConnectionFailed += MuxerConnectionFailed;
            connect.ConnectionRestored += MuxerConnectionRestored;
            connect.ErrorMessage += MuxerErrorMessage;
            connect.ConfigurationChanged += MuxerConfigurationChanged;
            connect.HashSlotMoved += MuxerHashSlotMoved;
            connect.InternalError += MuxerInternalError;
            return connect;
        

        #region 事件

        /// <summary>
        /// 配置更改时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void MuxerConfigurationChanged(object sender, EndPointEventArgs e)
        
            Console.WriteLine("Configuration changed: " + e.EndPoint);
        

        /// <summary>
        /// 发生错误时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void MuxerErrorMessage(object sender, RedisErrorEventArgs e)
        
            Console.WriteLine("ErrorMessage: " + e.Message);
        

        /// <summary>
        /// 重新建立连接之前的错误
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void MuxerConnectionRestored(object sender, ConnectionFailedEventArgs e)
        
            Console.WriteLine("ConnectionRestored: " + e.EndPoint);
        

        /// <summary>
        /// 连接失败 , 如果重新连接成功你将不会收到这个通知
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void MuxerConnectionFailed(object sender, ConnectionFailedEventArgs e)
        
            Console.WriteLine("重新连接:Endpoint failed: " + e.EndPoint + ", " + e.FailureType + (e.Exception == null ? "" : (", " + e.Exception.Message)));
        

        /// <summary>
        /// 更改集群
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void MuxerHashSlotMoved(object sender, HashSlotMovedEventArgs e)
        
            Console.WriteLine("HashSlotMoved:NewEndPoint" + e.NewEndPoint + ", OldEndPoint" + e.OldEndPoint);
        

        /// <summary>
        /// redis类库错误
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void MuxerInternalError(object sender, InternalErrorEventArgs e)
        
            Console.WriteLine("InternalError:Message" + e.Exception.Message);
        

        #endregion 事件
    

 

以上是关于redis分布式锁使用方法的主要内容,如果未能解决你的问题,请参考以下文章

redis 分布式锁

Redis实现分布式锁与Zookeeper实现分布式锁区别

分布式锁:二Redis锁

redis分布式锁深入

真正的 Redis 分布式锁,就该是这样实现的

分布式锁Redis分布式锁注解灵活实现