在NuGet直接搜索StackExchange.Redis,下载引用包;
帮助类
/*********************************** * Developer: Lio.Huang * Date:2018-11-21 **********************************/ using System; using System.Collections.Generic; using System.Linq; using StackExchange.Redis; using Newtonsoft.Json; using System.Threading.Tasks; namespace Banana.Utility.Redis { ////// Redis Base Utils /// public class RedisUtils { /// /// redis配置文件信息 /// public static string RedisPath = "172.16.3.82:6379"; /// /// 注册地址 /// /// redis connection string public static void Register(string redisPath) { RedisPath = redisPath; } private static ConnectionMultiplexer _instance = null; /// /// 使用一个静态属性来返回已连接的实例,如下列中所示。这样,一旦 ConnectionMultiplexer 断开连接,便可以初始化新的连接实例。 /// public static ConnectionMultiplexer Instance { get { return conn.Value; } } //public static ConnectionMultiplexer Instance //{ // get // { // //if (_instance == null) // //{ // // lock (_locker) // // { // if (_instance == null || !_instance.IsConnected) // { // _instance = ConnectionMultiplexer.Connect(RedisPath); // //注册如下事件 // _instance.ConnectionFailed += MuxerConnectionFailed; // _instance.ConnectionRestored += MuxerConnectionRestored; // _instance.ErrorMessage += MuxerErrorMessage; // _instance.HashSlotMoved += MuxerHashSlotMoved; // _instance.InternalError += MuxerInternalError; // } // // } // //} // return _instance; // } //} private static Lazy conn = new Lazy ( () => { _instance = ConnectionMultiplexer.Connect(RedisPath); //注册如下事件 _instance.ConnectionFailed += MuxerConnectionFailed; _instance.ConnectionRestored += MuxerConnectionRestored; _instance.ErrorMessage += MuxerErrorMessage; _instance.HashSlotMoved += MuxerHashSlotMoved; _instance.InternalError += MuxerInternalError; return _instance; } ); #region Keys /// /// 判断键是否存在 /// /// 数据库 /// 键值 /// public static bool KeyExists(int dbIndex, string key) { var db = Instance.GetDatabase(dbIndex); return db.KeyExists(key); } /// /// 为指定的键设置失效时间 /// /// 数据库 /// 键 /// 时间间隔 /// public static bool SetExpire(int dbIndex, string key, TimeSpan? expiry) { var db = Instance.GetDatabase(dbIndex); return db.KeyExpire(key, expiry); } /// /// 为指定的键设置失效时间 /// /// 数据库 /// 键 /// 时间间隔(秒) /// public static bool SetExpire(int dbIndex, string key, int timeout = 0) { var db = Instance.GetDatabase(dbIndex); return db.KeyExpire(key, DateTime.Now.AddSeconds(timeout)); } /// /// 删除键 /// /// 数据库 /// 键 /// public static bool KeyDelete(int dbIndex, string key) { var db = Instance.GetDatabase(dbIndex); return db.KeyDelete(key); } /// /// 键重命名 /// /// 数据库 /// 旧值 /// 新值 /// public static bool KeyRename(int dbIndex, string oldKey, string newKey) { var db = Instance.GetDatabase(dbIndex); return db.KeyRename(oldKey, newKey); } #endregion #region Strings /// /// 获取字符串数据 /// /// /// 数据库 /// Redis键 /// public static string StringGet(int dbIndex, string key) { var db = Instance.GetDatabase(dbIndex); if (db != null) { return db.StringGet(key); } return string.Empty; } /// /// 获取对象类型数据 /// /// /// 数据库 /// Redis键 /// public static T StringGet (int dbIndex, string key) where T : class { T data = default(T); var db = Instance.GetDatabase(dbIndex); if (db != null) { var value = db.StringGet(key); return ConvertObj (value); } return data; } /// /// 设置值类型的值 /// /// 数据库 /// 键 /// 值 public static bool StringSet(int dbIndex, string key, RedisValue value, TimeSpan? expiry) { var db = Instance.GetDatabase(dbIndex); return db.StringSet(key, value, expiry); } /// /// 设置对象类型的值 /// /// 数据库 /// 键 /// 值 public static bool StringSet (int dbIndex, string key, T value, TimeSpan? expiry) where T : class { if (value == default(T)) { return false; } var db = Instance.GetDatabase(dbIndex); return db.StringSet(key, ConvertJson(value), expiry); } #endregion #region Hashes /// /// Hash是否存在 /// /// 数据库 /// HashId /// 键 /// public static bool HashExists(int dbIndex, string hashId, string key) { var db = Instance.GetDatabase(dbIndex); return db.HashExists(key, hashId); } /// /// Hash长度 /// /// 数据库 /// HashId /// public static long HashLength(int dbIndex, string hashId) { var db = Instance.GetDatabase(dbIndex); var length = db.HashLength(hashId); return length; } /// /// 设置哈希值 /// /// 哈希值类型 /// 数据库 /// 哈希ID /// 键 /// 哈希值 /// public static bool HashSet (int dbIndex, string hashId, string key, T t) { var db = Instance.GetDatabase(dbIndex); return db.HashSet(hashId, key, ConvertJson(t)); } /// /// 获取哈希值 /// /// 哈希值类型 /// 数据库 /// 哈希ID /// 键 /// public static T HashGet (int dbIndex, string hashId, string key) { var db = Instance.GetDatabase(dbIndex); string value = db.HashGet(hashId, key); if (string.IsNullOrWhiteSpace(value)) return default(T); return ConvertObj (value); } /// /// 获取哈希值 /// /// 数据库 /// 哈希ID /// 键 /// public static string HashGet(int dbIndex, string hashId, string key) { var db = Instance.GetDatabase(dbIndex); return db.HashGet(hashId, key).ToString(); } /// /// 获取哈希值的所有键 /// /// 数据库 /// 哈希ID /// public static List<string> HashKeys(int dbIndex, string hashId) { var db = Instance.GetDatabase(dbIndex); var result = new List<string>(); var list = db.HashKeys(hashId).ToList(); if (list.Count > 0) { list.ForEach(x => { result.Add(ConvertObj<string>(x)); }); } return result; } /// /// 获取所有哈希值 /// /// 哈希值类型 /// 数据库 /// 哈希ID /// public static List HashGetAll (int dbIndex, string hashId) { var db = Instance.GetDatabase(dbIndex); var result = new List (); var list = db.HashGetAll(hashId).ToList(); if (list.Count > 0) { list.ForEach(x => { result.Add(ConvertObj (x.Value)); }); } return result; } /// /// 删除哈希值 /// /// 数据库 /// 哈希ID /// 键 /// public static bool HashDelete(int dbIndex, string hashId, string key) { var db = Instance.GetDatabase(dbIndex); return db.HashDelete(hashId, key); } #endregion #region Lists /// /// 集合长度 /// /// 数据库 /// 集合ID /// public static long ListLength(int dbIndex, string listId) { var db = Instance.GetDatabase(dbIndex); return db.ListLength(listId); } /// /// 向集合中添加元素 /// /// 元素类型 /// 数据库 /// 集合ID /// 元素值 /// public static long AddList (int dbIndex, string listId, List list) { var db = Instance.GetDatabase(dbIndex); if (list != null && list.Count > 0) { foreach (var item in list) { db.ListRightPush(listId, ConvertJson(item)); } } return db.ListLength(listId); } /// /// 获取集合元素(默认获取整个集合) /// /// 元素类型 /// 数据库 /// 集合ID /// 起始位置(0表示第1个位置) /// 结束位置(-1表示倒数第1个位置) /// public static List GetList (int dbIndex, string listId, long start = 0, long stop = -1) { var db = Instance.GetDatabase(dbIndex); var result = new List (); var list = db.ListRange(listId, start, stop).ToList(); if (list.Count > 0) { list.ForEach(x => { result.Add(ConvertObj (x)); }); } return result; } #endregion #region ZSet #region 同步方法 /// /// 添加一个值到Key /// /// /// 数据库 /// /// /// 排序分数,为空将获取集合中最大score加1 /// public static bool SortedSetAdd (int dbIndex, string key, T value, double? score = null) { var db = Instance.GetDatabase(dbIndex); double scoreNum = score ?? _GetScore(key, db); return db.SortedSetAdd(key, ConvertJson (value), scoreNum); } /// /// 添加一个集合到Key /// /// /// 数据库 /// /// /// 排序分数,为空将获取集合中最大score加1 /// public static long SortedSetAdd (int dbIndex, string key, List value, double? score = null) { var db = Instance.GetDatabase(dbIndex); double scoreNum = score ?? _GetScore(key, db); SortedSetEntry[] rValue = value.Select(o => new SortedSetEntry(ConvertJson (o), scoreNum++)).ToArray(); return db.SortedSetAdd(key, rValue); } /// /// 获取集合中的数量 /// /// 数据库 /// /// public static long SortedSetLength(int dbIndex,string key) { var db = Instance.GetDatabase(dbIndex); return db.SortedSetLength(key); } /// /// 获取指定起始值到结束值的集合数量 /// /// /// 数据库 /// /// 起始值 /// 结束值 /// public static long SortedSetLengthByValue (int dbIndex, string key, T startValue, T endValue) { var db = Instance.GetDatabase(dbIndex); var sValue = ConvertJson (startValue); var eValue = ConvertJson (endValue); return db.SortedSetLengthByValue(key, sValue, eValue); } /// /// 获取指定Key的排序Score值 /// /// /// 数据库 /// /// /// public static double? SortedSetScore (int dbIndex, string key, T value) { var db = Instance.GetDatabase(dbIndex); var rValue = ConvertJson (value); return db.SortedSetScore(key, rValue); } /// /// 获取指定Key中最小Score值 /// /// 数据库 /// /// public static double SortedSetMinScore(int dbIndex, string key) { var db = Instance.GetDatabase(dbIndex); double dValue = 0; var rValue = db.SortedSetRangeByRankWithScores(key, 0, 0, Order.Ascending).FirstOrDefault(); dValue = rValue != null ? rValue.Score : 0; return dValue; } /// /// 获取指定Key中最大Score值 /// /// 数据库 /// /// public static double SortedSetMaxScore(int dbIndex, string key) { var db = Instance.GetDatabase(dbIndex); double dValue = 0; var rValue = db.SortedSetRangeByRankWithScores(key, 0, 0, Order.Descending).FirstOrDefault(); dValue = rValue != null ? rValue.Score : 0; return dValue; } /// /// 删除Key中指定的值 /// /// 数据库 /// /// public static long SortedSetRemove (int dbIndex, string key, params T[] value) { var db = Instance.GetDatabase(dbIndex); var rValue = ConvertRedisValue (value); return db.SortedSetRemove(key, rValue); } /// /// 删除指定起始值到结束值的数据 /// /// /// 数据库 /// /// 起始值 /// 结束值 /// public static long SortedSetRemoveRangeByValue (int dbIndex, string key, T startValue, T endValue) { var db = Instance.GetDatabase(dbIndex); var sValue = ConvertJson (startValue); var eValue = ConvertJson (endValue); return db.SortedSetRemoveRangeByValue(key, sValue, eValue); } /// /// 删除 从 start 开始的 stop 条数据 /// /// 数据库 /// /// /// /// public static long SortedSetRemoveRangeByRank(int dbIndex, string key, long start, long stop) { var db = Instance.GetDatabase(dbIndex); return db.SortedSetRemoveRangeByRank(key, start, stop); } /// /// 根据排序分数Score,删除从 start 开始的 stop 条数据 /// /// 数据库 /// /// /// /// public static long SortedSetRemoveRangeByScore(int dbIndex, string key, double start, double stop) { var db = Instance.GetDatabase(dbIndex); return db.SortedSetRemoveRangeByScore(key, start, stop); } /// /// 获取从 start 开始的 stop 条数据 /// /// /// 数据库 /// /// 起始数 /// -1表示到结束,0为1条 /// 是否按降序排列 /// public static List SortedSetRangeByRank (int dbIndex, string key, long start = 0, long stop = -1, bool desc = false) { var db = Instance.GetDatabase(dbIndex); Order orderBy = desc ? Order.Descending : Order.Ascending; var rValue = db.SortedSetRangeByRank(key, start, stop, orderBy); return ConvetList (rValue); } #endregion #region 异步方法 /// /// 添加一个值到Key /// /// /// 数据库 /// /// /// 排序分数,为空将获取集合中最大score加1 /// public static async Task<bool> SortedSetAddAsync (int dbIndex, string key, T value, double? score = null) { var db = Instance.GetDatabase(dbIndex); double scoreNum = score ?? _GetScore(key, db); return await db.SortedSetAddAsync(key, ConvertJson (value), scoreNum); } /// /// 添加一个集合到Key /// /// /// 数据库 /// /// /// 排序分数,为空将获取集合中最大score加1 /// public static async Task<long> SortedSetAddAsync (int dbIndex, string key, List value, double? score = null) { var db = Instance.GetDatabase(dbIndex); double scoreNum = score ?? _GetScore(key, db); SortedSetEntry[] rValue = value.Select(o => new SortedSetEntry(ConvertJson (o), scoreNum++)).ToArray(); return await db.SortedSetAddAsync(key, rValue); } /// /// 获取集合中的数量 /// /// 数据库 /// /// public static async Task<long> SortedSetLengthAsync(int dbIndex, string key) { var db = Instance.GetDatabase(dbIndex); return await db.SortedSetLengthAsync(key); } /// /// 获取指定起始值到结束值的集合数量 /// /// /// 数据库 /// /// 起始值 /// 结束值 /// public static async Task<long> SortedSetLengthByValueAsync (int dbIndex, string key, T startValue, T endValue) { var db = Instance.GetDatabase(dbIndex); var sValue = ConvertJson (startValue); var eValue = ConvertJson (endValue); return await db.SortedSetLengthByValueAsync(key, sValue, eValue); } /// /// 获取指定Key中最大Score值 /// /// 数据库 /// /// public static async Task<double> SortedSetMaxScoreAsync(int dbIndex, string key) { var db = Instance.GetDatabase(dbIndex); double dValue = 0; var rValue = (await db.SortedSetRangeByRankWithScoresAsync(key, 0, 0, Order.Descending)).FirstOrDefault(); dValue = rValue != null ? rValue.Score : 0; return dValue; } /// /// 删除Key中指定的值 /// /// 数据库 /// /// public static async Task<long> SortedSetRemoveAsync (int dbIndex, string key, params T[] value) { var db = Instance.GetDatabase(dbIndex); var rValue = ConvertRedisValue (value); return await db.SortedSetRemoveAsync(key, rValue); } /// /// 删除指定起始值到结束值的数据 /// /// /// 数据库 /// /// 起始值 /// 结束值 /// public static async Task<long> SortedSetRemoveRangeByValueAsync (int dbIndex, string key, T startValue, T endValue) { var db = Instance.GetDatabase(dbIndex); var sValue = ConvertJson (startValue); var eValue = ConvertJson (endValue); return await db.SortedSetRemoveRangeByValueAsync(key, sValue, eValue); } /// /// 删除 从 start 开始的 stop 条数据 /// /// 数据库 /// /// /// /// public static async Task<long> SortedSetRemoveRangeByRankAsync(int dbIndex, string key, long start, long stop) { var db = Instance.GetDatabase(dbIndex); return await db.SortedSetRemoveRangeByRankAsync(key, start, stop); } #endregion #region private method /// /// 获取几个集合的交叉并集合,并保存到一个新Key中 /// /// /// Union:并集 Intersect:交集 Difference:差集 详见 /// 保存的新Key名称 /// 要操作的Key集合 /// private static long _SortedSetCombineAndStore(IDatabase db, SetOperation operation, string destination, params string[] keys) { RedisKey[] keyList = ConvertRedisKeysAddSysCustomKey(keys); var rValue = db.SortedSetCombineAndStore(operation, destination, keyList); return rValue; } /// /// 将string类型的Key转换成 型的Key,并添加前缀字符串 /// /// /// private static RedisKey[] ConvertRedisKeysAddSysCustomKey(params string[] redisKeys) => redisKeys.Select(redisKey => (RedisKey)redisKey).ToArray(); /// /// 获取指定Key中最大Score值, /// /// key名称,注意要先添加上Key前缀 /// private static double _GetScore(string key, IDatabase db) { double dValue = 0; var rValue = db.SortedSetRangeByRankWithScores(key, 0, 0, Order.Descending).FirstOrDefault(); dValue = rValue != null ? rValue.Score : 0; return dValue + 1; } #endregion #endregion #region SET /// /// Add the specified member to the set stored at key. Specified members that are already a member of this set are ignored. If key does not exist, a new set is created before adding the specified members. /// /// /// /// /// public static bool SetAdd (int dbIndex, string key, T value) { var db = Instance.GetDatabase(dbIndex); return db.SetAdd(key, ConvertJson(value)); } /// /// Add the specified member to the set stored at key. Specified members that are already a member of this set are ignored. If key does not exist, a new set is created before adding the specified members. /// /// /// /// /// public static async Task<bool> SetAddAsync (int dbIndex, string key, T value) { var db = Instance.GetDatabase(dbIndex); return await db.SetAddAsync(key, ConvertJson(value)); } /// /// Returns the members of the set resulting from the specified operation against the given sets. /// /// /// /// /// /// /// public static string[] SetCombine(int dbIndex, SetOperation operation, string firstKey, string secondKey) { var db = Instance.GetDatabase(dbIndex); var array = db.SetCombine(operation, firstKey, secondKey); return array.ToStringArray(); } /// /// Returns the members of the set resulting from the specified operation against the given sets. /// /// /// /// /// /// /// public static async Task<string[]> SetCombineAsync(int dbIndex, SetOperation operation, string firstKey, string secondKey) { var db = Instance.GetDatabase(dbIndex); var array = await db.SetCombineAsync(operation, firstKey, secondKey); return array.ToStringArray(); } /// /// Returns if member is a member of the set stored at key. /// /// /// /// /// Returns if member is a member of the set stored at key. public static bool SetContains (int dbIndex, string key, T value) { var db = Instance.GetDatabase(dbIndex); return db.SetContains(key, ConvertJson(value)); } /// /// Returns if member is a member of the set stored at key. /// /// /// /// /// Returns if member is a member of the set stored at key. public static async Task<bool> SetContainsAsync (int dbIndex, string key, T value) { var db = Instance.GetDatabase(dbIndex); return await db.SetContainsAsync(key, ConvertJson(value)); } /// /// 返回对应键值集合的长度|Returns the set cardinality (number of elements) of the set stored at key. /// /// /// /// public static long SetLength(int dbIndex, string key) { var db = Instance.GetDatabase(dbIndex); return db.SetLength(key); } /// /// 返回对应键值集合的长度|Returns the set cardinality (number of elements) of the set stored at key. /// /// /// /// public static async Task<long> SetLengthAsync(int dbIndex, string key) { var db = Instance.GetDatabase(dbIndex); return await db.SetLengthAsync(key); } /// /// 返回存储在键的集合值的所有成员|Returns all the members of the set value stored at key. /// /// /// /// public static List SetMembers (int dbIndex, string key) { var db = Instance.GetDatabase(dbIndex); var array = db.SetMembers(key); return ConvetList (array); } /// /// 返回存储在键的集合值的所有成员|Returns all the members of the set value stored at key. /// /// /// /// public static async Task > SetMembersAsync
(int dbIndex, string key) { var db = Instance.GetDatabase(dbIndex); var array = await db.SetMembersAsync(key); return ConvetList (array); } /// /// Move member from the set at source to the set at destination. This operation is atomic. In every given moment the element will appear to be a member of source or destination for other clients. When the specified element already exists in the destination set, it is only removed from the source set. /// /// /// /// /// /// public static bool SetMove (int dbIndex, string sourceKey, string destinationKey, T value) { var db = Instance.GetDatabase(dbIndex); return db.SetMove(sourceKey, destinationKey, ConvertJson(value)); } /// /// Move member from the set at source to the set at destination. This operation is atomic. In every given moment the element will appear to be a member of source or destination for other clients. When the specified element already exists in the destination set, it is only removed from the source set. /// /// /// /// /// /// public static async Task<bool> SetMoveAsync (int dbIndex, string sourceKey, string destinationKey, T value) { var db = Instance.GetDatabase(dbIndex); return await db.SetMoveAsync(sourceKey, destinationKey, ConvertJson(value)); } /// /// Removes and returns a random element from the set value stored at key. /// /// /// /// public static T SetPop (int dbIndex, string key) { var db = Instance.GetDatabase(dbIndex); var value = db.SetPop(key); return ConvertObj (value); } /// /// Removes and returns a random element from the set value stored at key. /// /// /// /// public static async Task SetPopAsync (int dbIndex, string key) { var db = Instance.GetDatabase(dbIndex); var value = await db.SetPopAsync(key); return ConvertObj (value); } /// /// Return a random element from the set value stored at key. /// /// /// /// public static T SetRandomMember (int dbIndex, string key) { var db = Instance.GetDatabase(dbIndex); var value = db.SetRandomMember(key); return ConvertObj (value); } /// /// Return a random element from the set value stored at key. /// /// /// /// public static async Task SetRandomMemberAsync (int dbIndex, string key) { var db = Instance.GetDatabase(dbIndex); var value = await db.SetRandomMemberAsync(key); return ConvertObj (value); } /// /// Return an array of count distinct elements if count is positive. If called with a negative count the behavior changes and the command is allowed to return the same element multiple times. In this case the numer of returned elements is the absolute value of the specified count. /// /// /// /// /// public static string[] SetRandomMember(int dbIndex, string key, long count) { var db = Instance.GetDatabase(dbIndex); return db.SetRandomMembers(key, count).ToStringArray(); } /// /// Return an array of count distinct elements if count is positive. If called with a negative count the behavior changes and the command is allowed to return the same element multiple times. In this case the numer of returned elements is the absolute value of the specified count. /// /// /// /// /// public static async Task<string[]> SetRandomMembersAsync(int dbIndex, string key, long count) { var db = Instance.GetDatabase(dbIndex); var array = await db.SetRandomMembersAsync(key, count); return array.ToStringArray(); } /// /// Remove the specified member from the set stored at key. Specified members that are not a member of this set are ignored. /// /// /// /// public static bool SetRemove(int dbIndex, string key, string value) { var db = Instance.GetDatabase(dbIndex); return db.SetRemove(key, value); } /// /// Remove the specified member from the set stored at key. Specified members that are not a member of this set are ignored. /// /// /// /// public static async Task<bool> SetRemoveAsync(int dbIndex, string key, string value) { var db = Instance.GetDatabase(dbIndex); return await db.SetRemoveAsync(key, value); } /// /// The SSCAN command is used to incrementally iterate over set; note: to resume an iteration via cursor, cast the original enumerable or enumerator to IScanningCursor. /// /// /// /// public static IEnumerable SetScan(int dbIndex, string key) { return Instance.GetDatabase(dbIndex).SetScan(key); } #endregion #region 当作消息代理中间件使用 一般使用更专业的消息队列来处理这种业务场景 /// /// 当作消息代理中间件使用 /// 消息组建中,重要的概念便是生产者,消费者,消息中间件。 /// /// /// /// public static long Publish(string channel, string message) { ISubscriber sub = Instance.GetSubscriber(); //return sub.Publish("messages", "hello"); return sub.Publish(channel, message); } /// /// 在消费者端得到该消息并输出 /// /// /// public static void Subscribe(string channelFrom) { ISubscriber sub = Instance.GetSubscriber(); sub.Subscribe(channelFrom, (channel, message) => { Console.WriteLine((string)message); }); } #endregion #region EventHandler /// /// 连接失败 , 如果重新连接成功你将不会收到这个通知 /// /// /// private static void MuxerConnectionFailed(object sender, ConnectionFailedEventArgs e) { } /// /// 重新建立连接之前的错误 /// /// /// private static void MuxerConnectionRestored(object sender, ConnectionFailedEventArgs e) { } /// /// 发生错误时 /// /// /// private static void MuxerErrorMessage(object sender, RedisErrorEventArgs e) { } /// /// 更改集群 /// /// /// private static void MuxerHashSlotMoved(object sender, HashSlotMovedEventArgs e) { // LogHelper.WriteInfoLog("HashSlotMoved:NewEndPoint" + e.NewEndPoint + ", OldEndPoint" + e.OldEndPoint); } /// /// redis类库错误 /// /// /// private static void MuxerInternalError(object sender, InternalErrorEventArgs e) { } #endregion #region 内部辅助方法 /// /// 将对象转换成string字符串 /// /// /// /// public static string ConvertJson (T value) { string result = value is string ? value.ToString() : JsonConvert.SerializeObject(value, Formatting.None); return result; } /// /// 将值集合转换成RedisValue集合 /// /// /// /// private static RedisValue[] ConvertRedisValue (params T[] redisValues) => redisValues.Select(o => (RedisValue)ConvertJson (o)).ToArray(); /// /// 将值反系列化成对象集合 /// /// /// /// public static List ConvetList (RedisValue[] values) { List result = new List (); foreach (var item in values) { var model = ConvertObj (item); result.Add(model); } return result; } /// /// 将值反系列化成对象 /// /// /// /// public static T ConvertObj (RedisValue value) { return value.IsNullOrEmpty ? default(T) : JsonConvert.DeserializeObject (value); } #endregion } }
在以上RedisUtils帮助类的基础上封装一次调用:
////// Redis帮助类 /// public class RedisHelper { /// /// 缓存失效时长 /// public const int EXPIRY = 30; private static int CheckDbIndex(int dbIndex) { if (dbIndex > 16 || dbIndex < 0) { dbIndex = 0; } return dbIndex; } /// /// 获取缓存数据 /// /// /// Redis数据库索引 /// Redis键 /// 从其他地方获取数据源,并缓存到Redis中 /// 过期时间,单位:分钟 /// public static T GetObject (int dbIndex, string key, Func fun, int? timeout = EXPIRY) where T : class { dbIndex = CheckDbIndex(dbIndex); T data = RedisUtils.StringGet (dbIndex, key); if (data != null) { return data; } if (fun != null) { data = fun(); } if (data != null) { TimeSpan? timeSp = null; if (timeout != null) timeSp = TimeSpan.FromMinutes(Convert.ToDouble(timeout)); RedisUtils.StringSet (dbIndex, key, data, timeSp); } return data; } /// /// KV /// /// /// 库 /// 键 /// 如找不到则从func获取 /// 超时时间 /// public static T GetObject_KV (int dbIndex, string key, Func func, TimeSpan? timeout) where T : class { T data = RedisUtils.StringGet (dbIndex, key); if (data != null) { return data; } if (func != null) { data = func(); } if (data != null) { RedisUtils.StringSet (dbIndex, key, data, timeout); } return data; } /// /// 异步获取缓存数据 /// /// 数据集类型 /// 数据库 /// 键 /// 从其他地方获取数据源,并缓存到Redis中 /// 过期时间,单位:分钟 /// public static async Task GetObjectAsync (int dbIndex, string key, Func fun, int timeout = EXPIRY) where T : class { dbIndex = CheckDbIndex(dbIndex); T data = RedisUtils.StringGet (dbIndex, key); if (data != null) { return data; } if (fun != null) { data = await Task.Run(() => { return fun(); }); } if (data != null) { RedisUtils.StringSet (dbIndex, key, data, TimeSpan.FromMinutes(timeout)); } return data; } /// /// 异步获取缓存数据 /// /// 数据集类型 /// 数据库 /// 键 /// 从其他地方获取数据源,并缓存到Redis中 /// 过期时间,单位:分钟 /// public static async Task GetObjectAsync (int dbIndex, string key, Func > fun, int timeout = EXPIRY) where T : class { dbIndex = CheckDbIndex(dbIndex); RedisCache cache = new RedisCache (); cache.CacheData = RedisUtils.StringGet (dbIndex, key); if (cache.CacheData != null) { return cache.CacheData; } var temp = await Task.Run(() => { return fun(); }); if (temp != null) cache = temp; if (cache.UseCache) { RedisUtils.StringSet (dbIndex, key, cache.CacheData, TimeSpan.FromMinutes(timeout)); } return cache.CacheData; } /// /// 异步获取数据集合 /// /// 数据集类型 /// 数据库 /// 键 /// 从其他地方获取数据源,并缓存到Redis中 /// 过期时间,单位:分钟 /// public static async Task > GetListAsync
(int dbIndex, string key, Func > fun, int timeout = EXPIRY) where T : class { dbIndex = CheckDbIndex(dbIndex); List
datas = RedisUtils.StringGet >(dbIndex, key); if (datas != null && datas.Count > 0) { return datas; } datas = await Task.Run(() => { return fun(); }); if (datas != null && datas.Count > 0) { RedisUtils.StringSet
>(dbIndex, key, datas, TimeSpan.FromMinutes(timeout)); } return datas; } ///
/// ZSet /// /// /// 库 /// 键 /// 如找不到则从func获取 /// public static List GetObject_ZSet (int dbIndex, string key, Func > func) where T : class { List
data = RedisUtils.SortedSetRangeByRank (dbIndex, key); if (data != null && data.Count > 0) { return data; } if (func != null) { data = func(); } if (data != null) { RedisUtils.SortedSetAdd (dbIndex, key, data); } return data; } /// /// Hash /// /// /// 库 /// hashID /// 键 /// 如找不到则从func获取 /// public static T GetObject_Hash (int dbIndex, string hashID, string key, Func func) where T : class { T data = RedisUtils.HashGet (dbIndex, hashID, key); if (data != null) { return data; } if (func != null) { data = func(); } if (data != null) { RedisUtils.HashSet (dbIndex, hashID, key, data); } return data; } }
修复
经过反复阅读源码和测试,还有得到源作者NickCraver的指导,ConnectionMultiplexer是线程安全的,在多线程的情况下,避免使用lock来作为单例来使用,出现的连接超时的情况。
It was not possible to connect to the redis server(s).ConnectTimeout
正确姿势在帮助类折叠代码里面。
测试源码:
static void TestRedis() { int dbIdx = 4; string key = "testKey"; Task.Run(()=> { while (true) { Task.Run(() => { RedisUtils.StringSet(dbIdx, key, DateTime.Now.ToString(), TimeSpan.FromSeconds(30)); }); Task.Run(() => { string v = RedisUtils.StringGet(dbIdx, key); Console.WriteLine("1:" + v); }); System.Threading.Thread.Sleep(100); } }); Task.Run(() => { while (true) { Task.Run(() => { RedisUtils.StringSet(dbIdx, key, DateTime.Now.ToString(), TimeSpan.FromSeconds(30)); }); Task.Run(() => { string v = RedisUtils.StringGet(dbIdx, key); Console.WriteLine("2:" + v); }); System.Threading.Thread.Sleep(100); } }); Task.Run(() => { while (true) { Task.Run(() => { RedisUtils.StringSet(dbIdx, key, DateTime.Now.ToString(), TimeSpan.FromSeconds(30)); }); Task.Run(() => { string v = RedisUtils.StringGet(dbIdx, key); Console.WriteLine("3:" + v); }); System.Threading.Thread.Sleep(100); } }); }
已封装在这里?