redis Distributed Lock Use

Quote:

StackExchange.Redis.dll

Redlock.CSharp.dll

RedLock.dll

 

Code:

  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 helper object management
     ///  </ Summary> 
    public  static  class RedisConnectionHelp
    {
        // System Key custom prefix 
        public  static  Readonly  String SysCustomKey ConfigurationManager.AppSettings = [ " redisKey " ] ?? "" ; // Get AppSettings from Redis ???

        //"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> 
        /// single embodiment acquires
         ///  </ 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;
            }
            // Register the following events 
            connect.ConnectionFailed + = MuxerConnectionFailed;
            connect.ConnectionRestored += MuxerConnectionRestored;
            connect.ErrorMessage += MuxerErrorMessage;
            connect.ConfigurationChanged += MuxerConfigurationChanged;
            connect.HashSlotMoved += MuxerHashSlotMoved;
            connect.InternalError += MuxerInternalError;
            return connect;
        }

        #region event

        /// <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> 
        /// re-establish the connection before the error
         ///  </ Summary> 
        ///  <param name = "SENDER"> </ param> 
        ///  <param name = "E"> </ param> 
        Private  static  void MuxerConnectionRestored ( Object SENDER, ConnectionFailedEventArgs E)
        {
            Console.WriteLine("ConnectionRestored: " + e.EndPoint);
        }

        ///  <the Summary> 
        /// connection fails, if successfully reconnect you will not receive this notice
         ///  </ the Summary> 
        ///  <param name = "SENDER"> </ param> 
        ///  < name = param "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 event 
    }

 

Guess you like

Origin www.cnblogs.com/lizhenhong/p/11162095.html