StackExchange.Redis 封装类

 

 

using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Configuration;
using Newtonsoft.Json;

namespace Services
{
    public class CacheService
    {
        private static CacheService instance = new CacheService();
        private static Logger logger = LogManager.GetCurrentClassLogger();

        int Default_Timeout = 20;//默认超时时间(单位秒)
        ConnectionMultiplexer redisConnection;
        IDatabase cache;

        /// 
        /// 连接超时设置
        /// 
        public int TimeOut
        {
            get
            {
                return Default_Timeout;
            }
            set
            {
                Default_Timeout = value;
            }
        }
        /// 
        /// 构造函数
        /// 
        private CacheService()
        {
            //redisConnection = ConnectionMultiplexer.Connect(ConfigurationManager.ConnectionStrings["RedisConnection"].ConnectionString);
            redisConnection = ConnectionMultiplexer.Connect(AppConfig.connectClientRedis);


            #region 注册事件
            //注册如下事件
            redisConnection.ConnectionFailed += MuxerConnectionFailed;
            redisConnection.ConnectionRestored += MuxerConnectionRestored;
            redisConnection.ErrorMessage += MuxerErrorMessage;
            redisConnection.ConfigurationChanged += MuxerConfigurationChanged;
            redisConnection.HashSlotMoved += MuxerHashSlotMoved;
            redisConnection.InternalError += MuxerInternalError;
            #endregion

            cache = redisConnection.GetDatabase();

        }
        /// 
        /// 实例化
        /// 
        /// 
        public static CacheService GetInstance()
        {
            return instance;
        }
        /// 
        /// 保存一个对象
        /// 
        /// 泛型对象
        /// key
        /// 对象
        /// 
        public bool Set(string key, T obj)
        {
            try
            {
                // var timeSpan = TimeSpan.FromSeconds(TimeOut);
                var json = ConvertJson(obj);
                return cache.StringSet(key, json);
            }
            catch (Exception ex)
            {
                logger.Error("=========== Class:CacheService method:Set ===========");
                logger.Error("=========== Key:" + key + "   value:" + ConvertJson(obj) + "===========");
                logger.Error(ex);
            }
            return false;

        }
        /// 
        /// 获取一个key的对象
        /// 
        /// 
        /// 
        /// 
        public T Get(string key)
        {
            RedisValue values = cache.StringGet(key);
            return ConvertObj(values);
        }
        public void Batch(IEnumerablestring, string>> keyValuePairs)
        {
            var batch = cache.CreateBatch();
            foreach (var k in keyValuePairs)
            {
                //var json = ConvertJson(k.Value);
                batch.StringSetAsync(k.Key, k.Value);
                //batch.SetAddAsync(k.Key, k.Value);
            }
            batch.Execute();
        }
        #region JSON,T 相互转换
        private string ConvertJson(T value)
        {
            string result = value is string ? value.ToString() : JsonConvert.SerializeObject(value);
            return result;
        }
        private T ConvertObj(RedisValue value)
        {
            if (value.IsNull)
            {
                return default(T);
            }
            return JsonConvert.DeserializeObject(value);
        }
        #endregion
        #region 事件

        /// 
        /// 配置更改时
        /// 
        /// 
        /// 
        private static void MuxerConfigurationChanged(object sender, EndPointEventArgs e)
        {
            logger.Info("Configuration changed: " + e.EndPoint);
        }

        /// 
        /// 发生错误时
        /// 
        /// 
        /// 
        private static void MuxerErrorMessage(object sender, RedisErrorEventArgs e)
        {
            logger.Error("ErrorMessage: " + e.Message);
        }

        /// 
        /// 重新建立连接之前的错误
        /// 
        /// 
        /// 
        private static void MuxerConnectionRestored(object sender, ConnectionFailedEventArgs e)
        {
            logger.Error("ConnectionRestored: " + e.EndPoint);
        }

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

        /// 
        /// 更改集群
        /// 
        /// 
        /// 
        private static void MuxerHashSlotMoved(object sender, HashSlotMovedEventArgs e)
        {
            logger.Info("HashSlotMoved:NewEndPoint" + e.NewEndPoint + ", OldEndPoint" + e.OldEndPoint);
        }

        /// 
        /// redis类库错误
        /// 
        /// 
        /// 
        private static void MuxerInternalError(object sender, InternalErrorEventArgs e)
        {
            logger.Error("InternalError:Message" + e.Exception.Message);
        }

        #endregion 事件
    }
}

 

转载于:https://www.cnblogs.com/cicada/p/10868249.html

你可能感兴趣的:(StackExchange.Redis 封装类)