• Redis缓存异常的容错实现方法( .net)


        using DotNet.Log;
    
        /// <summary>
        /// Redis缓存辅助类
        /// 
        /// 修改纪录
        /// 
        /// 2015-10-26 版本:1.0 SongBiao 创建文件。   
        /// 
        /// <author>
        ///     <name>SongBiao</name>
        ///     <date>2015-10-26</date>
        /// </author>
        /// </summary>
    
        public class RedisCacheHelper
        {
            #region 构造 单例模式
            ////默认缓存过期时间单位秒
            public static int secondsTimeOut = 30 * 60;
            // 数据库
            public static long InitialDb;
            // 地址
            public static string Url;
            private static PooledRedisClientManager _instance = null;
            private static object _locker = new Object();
            public static PooledRedisClientManager Instance
            {
                get
                {
                    if (_instance == null)
                    {
                        lock (_locker)
                        {
                            if (_instance == null)
                            {
                                InitialDb = SystemInfo.RedisInitialDb;
                                Url = SystemInfo.RedisHosts;
                                _instance = new PooledRedisClientManager(InitialDb, new string[] { Url });
                            }
                        }
                    }
                    return _instance;
                }
            }
            static RedisCacheHelper()
            {
            }
            public static RedisClient GetClient()
            {
                return (RedisClient)Instance.GetClient();
            }
            #endregion
    
            #region Key/Value 读取和存储
            /// <summary>
            /// 添加新缓存
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="key"></param>
            /// <param name="t"></param>
            /// <param name="timeout"></param>
            /// <returns></returns>
            public static bool Add<T>(string key, T t, int timeout)
            {
                using (var redisClient = RedisCacheHelper.GetClient())
                {
                    if (timeout > 0)
                    {
                        secondsTimeOut = timeout;
                    }
                    return redisClient.Add<T>(key, t, DateTime.Now.AddHours(secondsTimeOut));
                }
            }
    
            /// <summary>
            /// 添加新缓存
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="key"></param>
            /// <param name="t"></param>
            /// <param name="timeSpan"></param>
            /// <returns></returns>
            public static bool Add<T>(string key, T t, TimeSpan timeSpan)
            {
                using (var redisClient = RedisCacheHelper.GetClient())
                {
                    return redisClient.Add<T>(key, t, timeSpan);
                }
            }
    
            /// <summary>
            /// 设置缓存 用于修改
            /// 增加缓存异常处理次数
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="key">缓存建</param>
            /// <param name="t">缓存值</param>
            /// <param name="timeout">过期时间,单位秒,-1:不过期,0:默认过期时间</param>
            /// <returns></returns>
            public static bool Set<T>(string key, T t, int timeout = 0)
            {
                System.Func<string, T, bool> setKey = delegate(string redisKey, T redisT)
                                                {
                                                    using (var redisClient = RedisCacheHelper.GetClient())
                                                    {
                                                        if (timeout > 0)
                                                        {
                                                            secondsTimeOut = timeout;
                                                        }
                                                        return redisClient.Set<T>(redisKey, redisT, DateTime.Now.AddHours(secondsTimeOut));
                                                    }
                                                };
                int retryCounter = 0;
            Retry:
                try
                {
                    if (retryCounter > 0)
                    {
                        LogHelper.WriteErrorLog("public static bool Set<T>(string key, T t, int timeout = 0)设置Redis缓存数据重试,retryCounter:," + retryCounter, null);
                    }
                    return setKey(key, t);
                }
                catch (Exception ex)
                {
                    LogHelper.WriteErrorLog("public static T Get<T>(string key)获取Redis缓存数据异常,retryCounter:," + retryCounter + ",会重试3次,key:" + key + ",Message:" + ex.Message, ex);
                    if (retryCounter < 3)
                    {
                        Thread.Sleep(100);
                        retryCounter++;
                        goto Retry;
                    }
                }
                return false;
            }
    
            /// <summary>
            /// 设置缓存
            /// 增加缓存异常处理 3次
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="key"></param>
            /// <param name="t"></param>
            /// <param name="timeSpan"></param>
            /// <returns></returns>
            public static bool Set<T>(string key, T t, TimeSpan timeSpan)
            {
                System.Func<string, T, bool> setKey = delegate(string redisKey, T redisT)
                {
                    using (var redisClient = RedisCacheHelper.GetClient())
                    {
                        return redisClient.Set<T>(key, t, timeSpan);
                    }
                };
                int retryCounter = 0;
            Retry:
                try
                {
                    if (retryCounter > 0)
                    {
                        LogHelper.WriteErrorLog("public static bool Set<T>(string key, T t, int timeout = 0)设置Redis缓存数据重试,retryCounter:," + retryCounter, null);
                    }
                    return setKey(key, t);
                }
                catch (Exception ex)
                {
                    LogHelper.WriteErrorLog("public static T Get<T>(string key)获取Redis缓存数据异常,retryCounter:," + retryCounter + ",会重试3次,key:" + key + ",Message:" + ex.Message, ex);
                    if (retryCounter < 3)
                    {
                        Thread.Sleep(100);
                        retryCounter++;
                        goto Retry;
                    }
                }
                return false;
            }
    
            /// <summary>
            /// 获取
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="key"></param>
            /// <returns></returns>
            public static T Get<T>(string key)
            {
                if (!string.IsNullOrWhiteSpace(key))
                {
                    System.Func<string, T> getKey = delegate(string redisKey)
                    {
                        using (var redisClient = GetClient())
                        {
                            return redisClient.Get<T>(redisKey);
                        }
                    };
                    int retryCounter = 0;
                Retry:
                    try
                    {
                        if (retryCounter > 0)
                        {
                            LogHelper.WriteErrorLog("public static T Get<T>(string key)获取Redis缓存数据重试,retryCounter:," + retryCounter, null);
                        }
                        return getKey(key);
                    }
                    catch (Exception ex)
                    {
                        LogHelper.WriteErrorLog("public static T Get<T>(string key)获取Redis缓存数据异常,retryCounter:," + retryCounter + ",会重试3次,key:" + key + ",Message:" + ex.Message, ex);
                        if (retryCounter < 3)
                        {
                            Thread.Sleep(100);
                            retryCounter++;
                            goto Retry;
                        }
                    }
                }
                return default(T);
            }
    
            /// <summary>
            /// 根据key,返回byte[]格式
            /// </summary>
            /// <param name="key"></param>
            /// <returns></returns>
            public static byte[] GetValueByte(string key)
            {
                using (var redisClient = RedisCacheHelper.GetClient())
                {
                    byte[] value = redisClient.Get(key);
                    return value;
                }
            }
    
            ///  <summary>
            /// 使某个字段增加
            ///  </summary>
            ///  <param name="key"></param>
            ///  <param name="field"></param>
            /// <param name="incre"></param>
            /// <returns></returns>
            public static void SetHashIncr(string key, string field, long incre)
            {
                using (var redisClient = RedisCacheHelper.GetClient())
                {
                    redisClient.IncrementValueInHash(key, field, incre);
                }
            }
    
            /// <summary>
            /// 删除
            /// </summary>
            /// <param name="key"></param>
            /// <returns></returns>
            public static bool Remove(string key)
            {
                if (!string.IsNullOrWhiteSpace(key))
                {
                    using (var redisClient = RedisCacheHelper.GetClient())
                    {
                        return redisClient.Remove(key);
                    }
                }
                return false;
            }
    
            //public void Dispose()
            //{
            //    using (var redisClient = RedisCacheHelper.GetClient())
            //    {
            //        redisClient.Dispose();
            //    }
            //}
    
            #endregion
    
            #region List  操作
            ////对Set类型进行操作  
            //            client.AddItemToSet("a3", "ddd");  
            //            client.AddItemToSet("a3", "ccc");  
            //            client.AddItemToSet("a3", "tttt");  
            //            client.AddItemToSet("a3", "sssh");  
            //            client.AddItemToSet("a3", "hhhh");  
            //            System.Collections.Generic.HashSet<string> hashset=client.GetAllItemsFromSet("a3");  
            //            foreach (string str in hashset)  
            //            {  
            //                Console.WriteLine(str);  
            //            }  
            ////求并集  
            //            client.AddItemToSet("a3", "ddd");  
            //            client.AddItemToSet("a3", "ccc");  
            //            client.AddItemToSet("a3", "tttt");  
            //            client.AddItemToSet("a3", "sssh");  
            //            client.AddItemToSet("a3", "hhhh");  
            //            client.AddItemToSet("a4", "hhhh");  
            //            client.AddItemToSet("a4", "h777");  
            // System.Collections.Generic.HashSet<string> hashset=  client.GetUnionFromSets(new string[] { "a3","a4"});  
    
            //          foreach (string str in hashset)  
            //          {  
            //              Console.WriteLine(str);  
            //          }  
            ////求交集  
            // System.Collections.Generic.HashSet<string> hashset = client.GetIntersectFromSets(new string[] { “a3”, “a4” });  
            ////求差集.  
            // System.Collections.Generic.HashSet<string> hashset = client.GetDifferencesFromSet("a3",new string[] { "a4"});  
    
            ////Sorted Set类型
            // client.AddItemToSortedSet("a5", "ffff");  
            //            client.AddItemToSortedSet("a5","bbbb");  
            //            client.AddItemToSortedSet("a5", "gggg");  
            //            client.AddItemToSortedSet("a5", "cccc");  
            //            client.AddItemToSortedSet("a5", "waaa");  
            //            System.Collections.Generic.List<string> list =client.GetAllItemsFromSortedSet("a5");  
            //            foreach (string str in list)  
            //            {  
            //                Console.WriteLine(str);  
            //            }  
    
            /// <summary>
            /// 移除
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="key"></param>
            /// <param name="t"></param>
            /// <returns></returns>
            public static bool RemoveItemFromList<T>(string key, T t)
            {
                using (IRedisClient redis = RedisCacheHelper.GetClient())
                {
                    var redisTypedClient = redis.GetTypedClient<T>();
                    return redisTypedClient.RemoveItemFromList(redisTypedClient.Lists[key], t) > 0;
                }
            }
    
            /// <summary>
            /// 移除全部
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="key"></param>
            public static void ListRemoveAll<T>(string key)
            {
                using (IRedisClient redis = RedisCacheHelper.GetClient())
                {
                    var redisTypedClient = redis.GetTypedClient<T>();
                    redisTypedClient.Lists[key].RemoveAll();
                }
            }
    
            /// <summary>
            /// 获取list的总数量
            /// </summary>
            /// <param name="key"></param>
            /// <returns></returns>
            public static long ListCount(string key)
            {
                using (IRedisClient redis = RedisCacheHelper.GetClient())
                {
                    return redis.GetListCount(key);
                }
            }
    
            /// <summary>
            /// 获取指定范围的
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="key"></param>
            /// <param name="start"></param>
            /// <param name="count"></param>
            /// <returns></returns>
            public static List<T> ListGetRange<T>(string key, int start, int count)
            {
                using (IRedisClient redis = RedisCacheHelper.GetClient())
                {
                    var c = redis.GetTypedClient<T>();
                    return c.Lists[key].GetRange(start, start + count - 1);
                }
            }
            /// <summary>
            /// 获取全部的
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="key"></param>
            /// <returns></returns>
            public static List<T> GetAllList<T>(string key)
            {
                using (IRedisClient redis = RedisCacheHelper.GetClient())
                {
                    var c = redis.GetTypedClient<T>();
                    return c.Lists[key].GetRange(0, c.Lists[key].Count);
                }
            }
    
            /// <summary>
            /// 分页获取
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="key"></param>
            /// <param name="pageIndex"></param>
            /// <param name="pageSize"></param>
            /// <returns></returns>
            public static List<T> ListGetList<T>(string key, int pageIndex, int pageSize)
            {
                int start = pageSize * (pageIndex - 1);
                return ListGetRange<T>(key, start, pageSize);
            }
    
            /// <summary>
            /// 设置缓存过期
            /// </summary>
            /// <param name="key"></param>
            /// <param name="datetime"></param>
            public static void ListSetExpire(string key, DateTime datetime)
            {
                using (IRedisClient redis = RedisCacheHelper.GetClient())
                {
                    redis.ExpireEntryAt(key, datetime);
                }
            }
    
            /// <summary>
            /// 设置
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="key"></param>
            /// <param name="t"></param>
            public static void SetAdd<T>(string key, T t)
            {
                using (IRedisClient redis = RedisCacheHelper.GetClient())
                {
                    var redisTypedClient = redis.GetTypedClient<T>();
                    redisTypedClient.Sets[key].Add(t);
                }
            }
    
            /// <summary>
            /// 是否包含
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="key"></param>
            /// <param name="t"></param>
            /// <returns></returns>
            public static bool Contains<T>(string key, T t)
            {
                using (IRedisClient redis = RedisCacheHelper.GetClient())
                {
                    var redisTypedClient = redis.GetTypedClient<T>();
                    return redisTypedClient.Sets[key].Contains(t);
                }
            }
    
            /// <summary>
            /// 移除
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="key"></param>
            /// <param name="t"></param>
            /// <returns></returns>
            public static bool SetRemove<T>(string key, T t)
            {
                using (IRedisClient redis = RedisCacheHelper.GetClient())
                {
                    var redisTypedClient = redis.GetTypedClient<T>();
                    return redisTypedClient.Sets[key].Remove(t);
                }
            }
    
            /// <summary>
            /// 向list类型数据添加成员,向列表底部(右侧)添加
            /// </summary>
            /// <param name="list"></param>
            /// <param name="item"></param>
            public static void AddItemToListRight(string list, string item)
            {
                using (var redisClient = RedisCacheHelper.GetClient())
                {
                    redisClient.AddItemToList(list, item);
                }
            }
    
            /// <summary>
            /// 向list类型数据添加成员,向列表顶部(左侧)添加
            /// </summary>
            /// <param name="list"></param>
            /// <param name="item"></param>
            public static void AddItemToListLeft(string list, string item)
            {
                using (var redisClient = RedisCacheHelper.GetClient())
                {
                    redisClient.LPush(list, Encoding.Default.GetBytes(item));
                }
            }
    
            /// <summary>
            /// 从list类型数据读取所有成员
            /// </summary>
            public static List<string> GetAllItems(string list)
            {
                using (var redisClient = RedisCacheHelper.GetClient())
                {
                    List<string> listMembers = redisClient.GetAllItemsFromList(list);
                    return listMembers;
                }
            }
    
            /// <summary>
            /// 从list类型数据指定索引处获取数据,支持正索引和负索引
            /// </summary>
            /// <param name="list"></param>
            /// <param name="index"></param>
            /// <returns></returns>
            public static string GetItemFromList(string list, int index)
            {
                using (var redisClient = RedisCacheHelper.GetClient())
                {
                    string item = redisClient.GetItemFromList(list, index);
                    return item;
                }
            }
    
            /// <summary>
            /// 向列表底部(右侧)批量添加数据
            /// </summary>
            /// <param name="list"></param>
            /// <param name="values"></param>
            public static void GetRangeToList(string list, List<string> values)
            {
                using (var redisClient = RedisCacheHelper.GetClient())
                {
                    redisClient.AddRangeToList(list, values);
                }
            }
    
            /// <summary>
            /// 向集合中添加数据
            /// </summary>
            /// <param name="item"></param>
            /// <param name="str"></param>
            public static void GetItemToSet(string item, string str)
            {
                using (var redisClient = RedisCacheHelper.GetClient())
                {
                    redisClient.AddItemToSet(item, str);
                }
            }
    
            /// <summary>
            /// 获得集合中所有数据
            /// </summary>
            /// <param name="set"></param>
            /// <returns></returns>
            public static HashSet<string> GetAllItemsFromSet(string set)
            {
                using (var redisClient = RedisCacheHelper.GetClient())
                {
                    HashSet<string> items = redisClient.GetAllItemsFromSet(set);
                    return items;
                }
            }
    
            /// <summary>
            /// 获取fromSet集合和其他集合不同的数据
            /// </summary>
            /// <param name="fromSet"></param>
            /// <param name="toSet"></param>
            /// <returns></returns>
            public static HashSet<string> GetSetDiff(string fromSet, params string[] toSet)
            {
                using (var redisClient = RedisCacheHelper.GetClient())
                {
                    HashSet<string> diff = redisClient.GetDifferencesFromSet(fromSet, toSet);
                    return diff;
                }
            }
    
            /// <summary>
            /// 获得所有集合的并集
            /// </summary>
            /// <param name="set"></param>
            /// <returns></returns>
            public static HashSet<string> GetSetUnion(params string[] set)
            {
                using (var redisClient = RedisCacheHelper.GetClient())
                {
                    HashSet<string> union = redisClient.GetUnionFromSets(set);
                    return union;
                }
            }
    
            /// <summary>
            /// 获得所有集合的交集
            /// </summary>
            /// <param name="set"></param>
            /// <returns></returns>
            public static HashSet<string> GetSetInter(params string[] set)
            {
                using (var redisClient = RedisCacheHelper.GetClient())
                {
                    HashSet<string> inter = redisClient.GetIntersectFromSets(set);
                    return inter;
                }
            }
    
            /// <summary>
            /// 向有序集合中添加元素
            /// </summary>
            /// <param name="set"></param>
            /// <param name="value"></param>
            /// <param name="score"></param>
            public static void AddItemToSortedSet(string set, string value, long score)
            {
                using (var redisClient = RedisCacheHelper.GetClient())
                {
                    redisClient.AddItemToSortedSet(set, value, score);
                }
            }
    
            /// <summary>
            /// 获得某个值在有序集合中的排名,按分数的降序排列
            /// </summary>
            /// <param name="set"></param>
            /// <param name="value"></param>
            /// <returns></returns>
            public static long GetItemIndexInSortedSetDesc(string set, string value)
            {
                using (var redisClient = RedisCacheHelper.GetClient())
                {
                    long index = redisClient.GetItemIndexInSortedSetDesc(set, value);
                    return index;
                }
            }
    
            /// <summary>
            /// 获得某个值在有序集合中的排名,按分数的升序排列
            /// </summary>
            /// <param name="set"></param>
            /// <param name="value"></param>
            /// <returns></returns>
            public static long GetItemIndexInSortedSet(string set, string value)
            {
                using (var redisClient = RedisCacheHelper.GetClient())
                {
                    long index = redisClient.GetItemIndexInSortedSet(set, value);
                    return index;
                }
            }
    
            /// <summary>
            /// 获得有序集合中某个值得分数
            /// </summary>
            /// <param name="set"></param>
            /// <param name="value"></param>
            /// <returns></returns>
            public static double GetItemScoreInSortedSet(string set, string value)
            {
                using (var redisClient = RedisCacheHelper.GetClient())
                {
                    double score = redisClient.GetItemScoreInSortedSet(set, value);
                    return score;
                }
            }
    
            /// <summary>
            /// 获得有序集合中,某个排名范围的所有值
            /// </summary>
            /// <param name="set"></param>
            /// <param name="beginRank"></param>
            /// <param name="endRank"></param>
            /// <returns></returns>
            public static List<string> GetRangeFromSortedSet(string set, int beginRank, int endRank)
            {
                using (var redisClient = RedisCacheHelper.GetClient())
                {
                    List<string> valueList = redisClient.GetRangeFromSortedSet(set, beginRank, endRank);
                    return valueList;
                }
            }
    
            /// <summary>
            /// 获得有序集合中,某个分数范围内的所有值,升序
            /// </summary>
            /// <param name="set"></param>
            /// <param name="beginScore"></param>
            /// <param name="endScore"></param>
            /// <returns></returns>
            public static List<string> GetRangeFromSortedSet(string set, double beginScore, double endScore)
            {
                using (var redisClient = RedisCacheHelper.GetClient())
                {
                    List<string> valueList = redisClient.GetRangeFromSortedSetByHighestScore(set, beginScore, endScore);
                    return valueList;
                }
            }
    
            /// <summary>
            /// 获得有序集合中,某个分数范围内的所有值,降序
            /// </summary>
            /// <param name="set"></param>
            /// <param name="beginScore"></param>
            /// <param name="endScore"></param>
            /// <returns></returns>
            public static List<string> GetRangeFromSortedSetDesc(string set, double beginScore, double endScore)
            {
                using (var redisClient = RedisCacheHelper.GetClient())
                {
                    List<string> vlaueList = redisClient.GetRangeFromSortedSetByLowestScore(set, beginScore, endScore);
                    return vlaueList;
                }
            }
    
            /// <summary>
            /// 获得某个hash型key下的所有字段
            /// </summary>
            /// <param name="hashId"></param>
            /// <returns></returns>
            public static List<string> GetHashFields(string hashId)
            {
                using (var redisClient = RedisCacheHelper.GetClient())
                {
                    List<string> hashFields = redisClient.GetHashKeys(hashId);
                    return hashFields;
                }
            }
    
            /// <summary>
            /// 获得某个hash型key下的所有值
            /// </summary>
            /// <param name="hashId"></param>
            /// <returns></returns>
            public static List<string> GetHashValues(string hashId)
            {
                using (var redisClient = RedisCacheHelper.GetClient())
                {
                    List<string> hashValues = redisClient.GetHashKeys(hashId);
                    return hashValues;
                }
            }
    
            /// <summary>
            /// 获得hash型key某个字段的值
            /// </summary>
            /// <param name="key"></param>
            /// <param name="field"></param>
            public static string GetHashField(string key, string field)
            {
                using (var redisClient = RedisCacheHelper.GetClient())
                {
                    string value = redisClient.GetValueFromHash(key, field);
                    return value;
                }
            }
    
            /// <summary>
            /// 设置hash型key某个字段的值
            /// </summary>
            /// <param name="key"></param>
            /// <param name="field"></param>
            /// <param name="value"></param>
            public static void SetHashField(string key, string field, string value)
            {
                using (var redisClient = RedisCacheHelper.GetClient())
                {
                    redisClient.SetEntryInHash(key, field, value);
                }
            }
            #endregion
    
            #region Hash 操作
            /// <summary>
            /// 判断某个数据是否已经被缓存
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="key"></param>
            /// <param name="dataKey"></param>
            /// <returns></returns>
            public static bool HashExist<T>(string key, string dataKey)
            {
                using (IRedisClient redis = RedisCacheHelper.GetClient())
                {
                    return redis.HashContainsEntry(key, dataKey);
                }
            }
    
            /// <summary>
            /// 存储数据到hash表
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="key"></param>
            /// <param name="dataKey"></param>
            /// <returns></returns>
            public static bool HashSet<T>(string key, string dataKey, T t)
            {
                using (IRedisClient redis = RedisCacheHelper.GetClient())
                {
                    string value = ServiceStack.Text.JsonSerializer.SerializeToString<T>(t);
                    return redis.SetEntryInHash(key, dataKey, value);
                }
            }
    
            /// <summary>
            /// 移除hash中的某值
            /// </summary>
            /// <param name="key"></param>
            /// <param name="dataKey"></param>
            /// <returns></returns>
            public static bool HashRemove(string key, string dataKey)
            {
                using (IRedisClient redis = RedisCacheHelper.GetClient())
                {
                    return redis.RemoveEntryFromHash(key, dataKey);
                }
            }
            /// <summary>
            /// 移除整个hash
            /// </summary>
            /// <param name="key"></param>
            /// <returns></returns>
            public static bool HashRemove(string key)
            {
                using (IRedisClient redis = RedisCacheHelper.GetClient())
                {
                    return redis.Remove(key);
                }
            }
            /// <summary>
            /// 从hash表获取数据
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="key"></param>
            /// <param name="dataKey"></param>
            /// <returns></returns>
            public static T HashGet<T>(string key, string dataKey)
            {
                using (IRedisClient redis = RedisCacheHelper.GetClient())
                {
                    string value = redis.GetValueFromHash(key, dataKey);
                    return ServiceStack.Text.JsonSerializer.DeserializeFromString<T>(value);
                }
            }
            /// <summary>
            /// 获取整个hash的数据
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="key"></param>
            /// <returns></returns>
            public static List<T> HashGetAll<T>(string key)
            {
                using (IRedisClient redis = RedisCacheHelper.GetClient())
                {
                    var list = redis.GetHashValues(key);
                    if (list != null && list.Count > 0)
                    {
                        List<T> result = new List<T>();
                        foreach (var item in list)
                        {
                            var value = ServiceStack.Text.JsonSerializer.DeserializeFromString<T>(item);
                            result.Add(value);
                        }
                        return result;
                    }
                    return null;
                }
            }
            /// <summary>
            /// 设置缓存过期
            /// </summary>
            /// <param name="key"></param>
            /// <param name="datetime"></param>
            public static void HashSetExpire(string key, DateTime datetime)
            {
                using (IRedisClient redis = RedisCacheHelper.GetClient())
                {
                    redis.ExpireEntryAt(key, datetime);
                }
            }
            #endregion
    
            #region SortedSet 操作
            /// <summary>
            ///  添加数据到 SortedSet
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="key"></param>
            /// <param name="t"></param>
            /// <param name="score"></param>
            public static bool SortedSetAdd<T>(string key, T t, double score)
            {
                using (IRedisClient redis = RedisCacheHelper.GetClient())
                {
                    string value = ServiceStack.Text.JsonSerializer.SerializeToString<T>(t);
                    return redis.AddItemToSortedSet(key, value, score);
                }
            }
            /// <summary>
            /// 移除数据从SortedSet
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="key"></param>
            /// <param name="t"></param>
            /// <returns></returns>
            public static bool SortedSetRemove<T>(string key, T t)
            {
                using (IRedisClient redis = RedisCacheHelper.GetClient())
                {
                    string value = ServiceStack.Text.JsonSerializer.SerializeToString<T>(t);
                    return redis.RemoveItemFromSortedSet(key, value);
                }
            }
            /// <summary>
            /// 修剪SortedSet
            /// </summary>
            /// <param name="key"></param>
            /// <param name="size">保留的条数</param>
            /// <returns></returns>
            public static long SortedSetTrim(string key, int size)
            {
                using (IRedisClient redis = RedisCacheHelper.GetClient())
                {
                    return redis.RemoveRangeFromSortedSet(key, size, 9999999);
                }
            }
            /// <summary>
            /// 获取SortedSet的长度
            /// </summary>
            /// <param name="key"></param>
            /// <returns></returns>
            public static long SortedSetCount(string key)
            {
                using (IRedisClient redis = RedisCacheHelper.GetClient())
                {
                    return redis.GetSortedSetCount(key);
                }
            }
    
            /// <summary>
            /// 获取SortedSet的分页数据
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="key"></param>
            /// <param name="pageIndex"></param>
            /// <param name="pageSize"></param>
            /// <returns></returns>
            public static List<T> SortedSetGetList<T>(string key, int pageIndex, int pageSize)
            {
                using (IRedisClient redis = RedisCacheHelper.GetClient())
                {
                    var list = redis.GetRangeFromSortedSet(key, (pageIndex - 1) * pageSize, pageIndex * pageSize - 1);
                    if (list != null && list.Count > 0)
                    {
                        List<T> result = new List<T>();
                        foreach (var item in list)
                        {
                            var data = ServiceStack.Text.JsonSerializer.DeserializeFromString<T>(item);
                            result.Add(data);
                        }
                        return result;
                    }
                }
                return null;
            }
    
    
            /// <summary>
            /// 获取SortedSet的全部数据
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="key"></param>
            /// <returns></returns>
            public static List<T> SortedSetGetListAll<T>(string key)
            {
                using (IRedisClient redis = RedisCacheHelper.GetClient())
                {
                    var list = redis.GetRangeFromSortedSet(key, 0, 9999999);
                    if (list != null && list.Count > 0)
                    {
                        List<T> result = new List<T>();
                        foreach (var item in list)
                        {
                            var data = ServiceStack.Text.JsonSerializer.DeserializeFromString<T>(item);
                            result.Add(data);
                        }
                        return result;
                    }
                }
                return null;
            }
    
            /// <summary>
            /// 设置缓存过期
            /// </summary>
            /// <param name="key"></param>
            /// <param name="datetime"></param>
            public static void SortedSetSetExpire(string key, DateTime datetime)
            {
                using (IRedisClient redis = RedisCacheHelper.GetClient())
                {
                    redis.ExpireEntryAt(key, datetime);
                }
            }
    
            //public static double SortedSet_GetItemScore<T>(string key,T t)
            //{
            //    using (IRedisClient redis = prcm.GetClient())
            //    {
            //        var data = ServiceStack.Text.JsonSerializer.SerializeToString<T>(t);
            //        return redis.GetItemScoreInSortedSet(key, data);
            //    }
            //    return 0;
            //}
    
            #endregion
    
            #region 链表 操作
            /// <summary>
            /// 获取链表数据
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="listId"></param>
            /// <returns></returns>
            public static IEnumerable<T> GetList<T>(string listId)
            {
                using (var redisClient = RedisCacheHelper.GetClient())
                {
                    IRedisTypedClient<T> iredisClient = redisClient.As<T>();
                    return iredisClient.Lists[listId];
                }
            }
    
            /// <summary>
            /// IEnumerable数据添加到链表
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="listId"></param>
            /// <param name="values"></param>
            /// <param name="timeout"></param>
            public static void AddList<T>(string listId, IEnumerable<T> values, int timeout = 0)
            {
                using (var redisClient = RedisCacheHelper.GetClient())
                {
                    redisClient.Expire(listId, 60);
                    IRedisTypedClient<T> iredisClient = redisClient.As<T>();
                    if (timeout >= 0)
                    {
                        if (timeout > 0)
                        {
                            secondsTimeOut = timeout;
                        }
                        redisClient.Expire(listId, secondsTimeOut);
                    }
                    var redisList = iredisClient.Lists[listId];
                    redisList.AddRange(values);
                    iredisClient.Save();
                }
            }
    
            /// <summary>
            /// 添加单个实体到链表中
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="listId"></param>
            /// <param name="item"></param>
            /// <param name="timeout"></param>
            public static void AddEntityToList<T>(string listId, T item, int timeout = 0)
            {
                using (var redisClient = RedisCacheHelper.GetClient())
                {
                    IRedisTypedClient<T> iredisClient = redisClient.As<T>();
                    if (timeout >= 0)
                    {
                        if (timeout > 0)
                        {
                            secondsTimeOut = timeout;
                        }
                        redisClient.Expire(listId, secondsTimeOut);
                    }
                    var redisList = iredisClient.Lists[listId];
                    redisList.Add(item);
                    iredisClient.Save();
                }
            }
    
            /// <summary>
            /// 在链表中删除单个实体
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="listId"></param>
            /// <param name="t"></param>
            public static void RemoveEntityFromList<T>(string listId, T t)
            {
                using (var redisClient = RedisCacheHelper.GetClient())
                {
                    IRedisTypedClient<T> iredisClient = redisClient.As<T>();
                    var redisList = iredisClient.Lists[listId];
                    redisList.RemoveValue(t);
                    iredisClient.Save();
                }
            }
    
            /// <summary>
            /// 根据lambada表达式删除符合条件的实体
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="listId"></param>
            /// <param name="func"></param>
            public static void RemoveEntityFromList<T>(string listId, Func<T, bool> func)
            {
                using (IRedisTypedClient<T> iredisClient = RedisCacheHelper.GetClient().As<T>())
                {
                    var redisList = iredisClient.Lists[listId];
                    T value = redisList.Where(func).FirstOrDefault();
                    redisList.RemoveValue(value);
                    iredisClient.Save();
                }
            }
            #endregion
    
        }

    目前对Get和Set进行了容错处理,3次内可以接收。

  • 相关阅读:
    C# 消息队列 RabbitMQ
    C# webapi简单学习
    Navicat Premium 12注册机使用教程
    .net WCF简单练习
    MSDN 我告诉你(资源库)
    Dapper查询返回Datatable
    day55 无连接,无状态,会话跟踪、cookie、django中操作cookie、session、django中操作session
    day54 锁和事务、ajax、中间件
    day53 url别名反向解析、ORM多表操作、聚合查询、分组查询、F查询、Q查询
    day52
  • 原文地址:https://www.cnblogs.com/hnsongbiao/p/5045605.html
Copyright © 2020-2023  润新知