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 = * ;
// 数据库
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 > )
{
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 = )
{
System.Func<string, T, bool> setKey = delegate(string redisKey, T redisT)
{
using (var redisClient = RedisCacheHelper.GetClient())
{
if (timeout > )
{
secondsTimeOut = timeout;
}
return redisClient.Set<T>(redisKey, redisT, DateTime.Now.AddHours(secondsTimeOut));
}
};
int retryCounter = ;
Retry:
try
{
if (retryCounter > )
{
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 < )
{
Thread.Sleep();
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 = ;
Retry:
try
{
if (retryCounter > )
{
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 < )
{
Thread.Sleep();
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 = ;
Retry:
try
{
if (retryCounter > )
{
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 < )
{
Thread.Sleep();
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) > ;
}
} /// <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 - );
}
}
/// <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(, 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 - );
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 > )
{
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, );
}
}
/// <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 - ) * pageSize, pageIndex * pageSize - );
if (list != null && list.Count > )
{
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, , );
if (list != null && list.Count > )
{
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 = )
{
using (var redisClient = RedisCacheHelper.GetClient())
{
redisClient.Expire(listId, );
IRedisTypedClient<T> iredisClient = redisClient.As<T>();
if (timeout >= )
{
if (timeout > )
{
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 = )
{
using (var redisClient = RedisCacheHelper.GetClient())
{
IRedisTypedClient<T> iredisClient = redisClient.As<T>();
if (timeout >= )
{
if (timeout > )
{
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次内可以接收。
Redis缓存异常的容错实现方法( .net)的更多相关文章
- Java 使用Redis缓存工具的图文详细方法
开始在 Java 中使用 Redis 前, 我们需要确保已经安装了 redis 服务及 Java redis 驱动,且你的机器上能正常使用 Java. (1)Java的安装配置可以参考我们的 Java ...
- Windows环境下使用Redis缓存工具的图文详细方法
一.简介 redis是一个key-value存储系统.和Memcached类似,它支持存储的value类型相对更多,包括string(字符串).list(链表).set(集合)和zset(有序集合). ...
- redis结合自定义注解实现基于方法的注解缓存,及托底缓存的实现
本次分享如何使用redis结合自定义注解实现基于方法的注解缓存,及托底缓存的实现思路 现在的互联网公司大多数都是以Redis作为缓存,使用缓存的优点就不赘述了,写这篇文章的目的就是想帮助同学们如 ...
- Redis获取缓存异常:java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to XXX
Redis获取缓存异常:java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to XXX. 出现这种异常,我需要自 ...
- Redis缓存篇(四)缓存异常
这一节,我们来学习一下缓存异常.缓存异常有四种类型,分别是缓存和数据库的数据不一致.缓存雪崩.缓存击穿和缓存穿透. 下面通过了解这四种缓存异常的原理和应对方法. 缓存和数据库的数据不一致 缓存和数据库 ...
- $.ajax()方法详解 ajax之async属性 【原创】详细案例解剖——浅谈Redis缓存的常用5种方式(String,Hash,List,set,SetSorted )
$.ajax()方法详解 jquery中的ajax方法参数总是记不住,这里记录一下. 1.url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址. 2.type: 要求为Str ...
- 使用方法拦截机制在不修改原逻辑基础上为 spring MVC 工程添加 Redis 缓存
首先,相关文件:链接: https://pan.baidu.com/s/1H-D2M4RfXWnKzNLmsbqiQQ 密码: 5dzk 文件说明: redis-2.4.5-win32-win64.z ...
- 【Azure Redis 缓存】Azure Redis出现了超时问题后,记录一步一步的排查出异常的客户端连接和所执行命令的步骤
问题描述 Azure Redis在使用的过程中,多次无规律的出现超时问题.抓取到客户端的异常错误后,想进一步的分析是何原因导致了如下异常呢? Timeout awaiting response (ou ...
- AbpVnext使用分布式IDistributedCache Redis缓存(自定义扩展方法)
AbpVnext使用分布式IDistributedCache缓存from Redis(带自定义扩展方法) 我的依赖包的主要版本以及Redis依赖如下 1:添加依赖 <PackageReferen ...
随机推荐
- 创建Android Virtual Device
参考http://book.51cto.com/art/201302/380026.htm Linux版的Android SDK没有提供可视化的AVD Manager管理工具,创建AVD可以使用and ...
- POJ1463 Strategic game (最小点覆盖 or 树dp)
题目链接:http://poj.org/problem?id=1463 给你一棵树形图,问最少多少个点覆盖所有的边. 可以用树形dp做,任选一点,自底向上回溯更新. dp[i][0] 表示不选i点 覆 ...
- 使用dbcp : BasicDataSource
需要 commons-dbcp2 com.oracle.ojdbc6 <dependency> <groupId>org.apache.commons</groupId& ...
- window 方法:延时 和 重复
window 方法 var timer = setTimeout(closeFunc,10*1000); function closeFunc(){ alert('close'); }
- 字符编解码的故事(ASCII,ANSI,Unicode,Utf-8)
很久很久以前,有一群人,他们决定用8个可以开合的晶体管来组合成不同的状态,以表示世界上的万物.他们认为8个开关状态作为原子单位很好,于是他们把这称为"字节". 再后来,他们又做了一 ...
- android 绘图之Canvas,Paint类
Canvas,Paint 1.在android 绘图但中经常要用到Canvas和Paint类,Canvas好比是一张画布,上面已经有你想绘制图画的轮廓了,而Paint就好比是画笔,就要给Canvas进 ...
- INNO&&DELPHI
好久不弄delphi了,再次见到inno,居然不知所措~ 让人亲切的 var,又见到了.而如今,到处可见. 整目录复制 Flags: igNoreversion recursesubdirs crea ...
- Maven仓库的布局
任何一个构件都有其唯一的坐标,根据这个坐标可以定义其在仓库中的唯一存储路径,这便是Maven的仓库布局方式.例如log4j:log4j:1.2.15这一依赖,其对应的仓库路径为log4j/log4j/ ...
- Objective-C运行时编程 - 方法混写 Method Swizzling
摘要: 本文描述方法混写对实例.类.父类.不存在的方法等情况处理,属于Objective-C(oc)运行时(runtime)编程范围. 编程环境:Xcode 6.1.1, Yosemite,iOS 8 ...
- 复选框输入Android Studio 如果修改LogCat的颜色,默认全是黑色看着挺不舒服的
今天一直在查找复选框输入之类的问题,上午正好有机会和大家分享一下. 怎么找到并表现LogCat这里就不需要再讲了吧,主要说一下本篇的主题,如何修改他的颜色 .我们在使用Eclipse的时候应该都用过L ...