using Services.Extensions; using Newtonsoft.Json; using StackExchange.Redis; using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; namespace Services.Tool { #region ConnectionMultiplexer对象管理帮助类 /// /// ConnectionMultiplexer对象管理帮助类 /// public static class RedisConnectionHelp { /// /// 系统自定义Key前缀 /// public static readonly string SysCustomKey = ConfigHelper.GetConfigString("RedisKey") ?? ""; /// /// 链接字符串 /// 127.0.0.1:6379,allowadmin=true /// private static readonly string RedisConnectionString = ConfigHelper.GetConfigString("RedisConn"); /// /// 单例初始化并发锁 /// private static readonly object Locker = new object(); /// /// 默认实例 /// private static ConnectionMultiplexer _instance; /// /// 链接池 /// private static readonly ConcurrentDictionary ConnectionCache = new ConcurrentDictionary(); /// /// 获取默认单例 /// public static ConnectionMultiplexer Instance { get { if (_instance == null) { lock (Locker) { if (_instance == null || !_instance.IsConnected) { _instance = GetManager(); } } } if (!_instance.IsConnected) { _instance.PublishReconfigure(); } return _instance; } } /// /// 缓存链接 /// /// /// public static ConnectionMultiplexer GetConnectionMultiplexer(string connectionString) { if (!ConnectionCache.ContainsKey(connectionString)) { ConnectionCache[connectionString] = GetManager(connectionString); } return ConnectionCache[connectionString]; } /// /// 从配置/字符串获取链接 /// /// /// private static ConnectionMultiplexer GetManager(string connectionString = null) { connectionString = connectionString ?? RedisConnectionString; var connect = ConnectionMultiplexer.Connect(connectionString); //注册如下事件 connect.ConnectionFailed += MuxerConnectionFailed; connect.ConnectionRestored += MuxerConnectionRestored; connect.ErrorMessage += MuxerErrorMessage; connect.ConfigurationChanged += MuxerConfigurationChanged; connect.HashSlotMoved += MuxerHashSlotMoved; connect.InternalError += MuxerInternalError; return connect; } #region 事件 /// /// 配置更改时 /// /// /// private static void MuxerConfigurationChanged(object sender, EndPointEventArgs e) { Console.WriteLine("Configuration changed: " + e.EndPoint); } /// /// 发生错误时 /// /// /// private static void MuxerErrorMessage(object sender, RedisErrorEventArgs e) { Console.WriteLine("ErrorMessage: " + e.Message); } /// /// 重新建立连接之前的错误 /// /// /// private static void MuxerConnectionRestored(object sender, ConnectionFailedEventArgs e) { Console.WriteLine("ConnectionRestored: " + e.EndPoint); } /// /// 连接失败 , 如果重新连接成功你将不会收到这个通知 /// /// /// private static void MuxerConnectionFailed(object sender, ConnectionFailedEventArgs e) { Console.WriteLine("重新连接:Endpoint failed: " + e.EndPoint + ", " + e.FailureType + (e.Exception == null ? "" : (", " + e.Exception.Message))); } /// /// 更改集群 /// /// /// private static void MuxerHashSlotMoved(object sender, HashSlotMovedEventArgs e) { Console.WriteLine("HashSlotMoved:NewEndPoint" + e.NewEndPoint + ", OldEndPoint" + e.OldEndPoint); } /// /// redis类库错误 /// /// /// private static void MuxerInternalError(object sender, InternalErrorEventArgs e) { Console.WriteLine("InternalError:Message" + e.Exception.Message); } #endregion 事件 } #endregion /// /// redis 数据库操作帮助类 /// public class StackChangeRedisHelper { //执行顺序---静态字段---静态构造函数---构造函数 #region 键值前缀 /// /// 数据库缓存前缀,区分站点 /// public static string systemKey { get { return RedisConnectionHelp.SysCustomKey + "_"; } } /// /// 对每个key进行前缀的添加处理 /// /// 原始key /// public static string AddSysCustomKey(string oldKey) { string snqwe = string.Format("{0}{1}", systemKey, oldKey); return snqwe; } #endregion #region 数据集/数据库索引 /// /// 数据集/数据库索引 /// private static int dbindex = -1; /// /// 数据集/数据库索引 /// public static int DBIndex { get { return dbindex; } set { dbindex = value; } } #endregion #region 客户端连接 /// /// redis 客户端服务 /// public static ConnectionMultiplexer Client { get { return RedisConnectionHelp.Instance; } } #endregion #region DB数据集/数据库实例 /// /// redis DB数据库实例 /// public static IDatabase Db { get { return Client.GetDatabase(DBIndex); } } #endregion #region 辅助方法 /// /// 将泛型类型序列化Json字符串 /// /// 泛型 T /// 序列化实例 /// 返回序列化 字符串 private static string ConvertJson(T value) { return value is string ? value.ToString() : JsonConvert.SerializeObject(value, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, Formatting = Formatting.None }); } /// /// 反序列化 /// /// 泛型T /// 反序列化 字符串 /// 返回 泛型T 实例 private static T ConvertObj(string value) { if (typeof(T).Name.ToLower().Equals("string")) { return (T)(Object)value; } return JsonConvert.DeserializeObject(value); } /// /// 序列化列表 /// /// 泛型T /// RedisValue 集合 /// 返回 泛型T的 Lis 实例T集合 private static List ConvetList(RedisValue[] values) { List result = new List(); if (typeof(T).Name.ToLower().Equals("string")) { return values as List; } values.ForEach(d => { result.Add(ConvertObj(d)); }); return result; } #endregion #region Redis String /// /// 设置Redis String缓存,根据键值 (key自动添加系统名称前缀) /// /// 原始key /// 值对象 /// 设置超时 /// 存入动作 0 Always 无论是否存在现有值,都应该执行该操作 1 xists 该操作应该只在存在值时才执行 2 NotExists 该操作应该只在不存在值的情况下执行 /// 与给定命令关联的行为标记 public static void StringSet(string key, object value, TimeSpan? expiry = default(TimeSpan?), When when = When.Always, CommandFlags flags = CommandFlags.None) { StringSetCompleteKey(AddSysCustomKey(key), value, expiry, when, flags); } /// /// 设置Redis String缓存,根据键值(完整键值,不包含系统名称前缀) /// /// 全key /// 值对象 /// 设置超时 /// 存入动作 0 Always 无论是否存在现有值,都应该执行该操作 1 xists 该操作应该只在存在值时才执行 2 NotExists 该操作应该只在不存在值的情况下执行 /// 与给定命令关联的行为标记 public static void StringSetCompleteKey(string CompleteKey, object value, TimeSpan? expiry = default(TimeSpan?), When when = When.Always, CommandFlags flags = CommandFlags.None) { Db.StringSet(CompleteKey, ConvertJson(value), expiry, when, flags); } /// /// 设置Redis String缓存,根据键值 (key自动添加系统名称前缀) /// /// 原始key /// 值对象 /// 设置超时 /// 存入动作 0 Always 无论是否存在现有值,都应该执行该操作 1 xists 该操作应该只在存在值时才执行 2 NotExists 该操作应该只在不存在值的情况下执行 /// 与给定命令关联的行为标记 public static void StringAppend(string key, object value, CommandFlags flags = CommandFlags.None) { Db.StringAppend(AddSysCustomKey(key), ConvertJson(value), flags); } /// /// 设置键的字符串值并返回其旧值 (key自动添加系统名称前缀) /// /// 泛型T /// 原始key /// 值对象 /// 返回泛型T实例 旧值 public static T StringGetAndSet(string key, object value) { return StringGetAndSetCompleteKey(AddSysCustomKey(key), value); } /// /// 设置键的字符串值并返回其旧值(完整键值,不包含系统名称前缀) /// /// 泛型T /// 全key /// 值对象 /// 返回泛型T实例 旧值 public static T StringGetAndSetCompleteKey(string CompleteKey, object value) { string str = Db.StringGetSet(CompleteKey, ConvertJson(value)); if (!string.IsNullOrWhiteSpace(str)) { return ConvertObj(str); } return default(T); } /// /// 获取Redis String缓存,根据键值 (key自动添加系统名称前缀) /// /// 泛型T /// 原始key /// 返回泛型T实例 public static T StringGet(string key) { return StringGetCompleteKey(AddSysCustomKey(key)); } /// /// 获取Redis String缓存,根据键值(完整键值,不包含系统名称前缀) /// /// 泛型T /// 全key /// 返回泛型T实例 public static T StringGetCompleteKey(string CompleteKey) { string str = Db.StringGet(CompleteKey); if (!string.IsNullOrWhiteSpace(str)) { return ConvertObj(str); } return default(T); } #endregion #region Redis Hash /// /// 判断该字段是否存在 hash 中 (key自动添加系统名称前缀) /// /// 原始key /// hash Key /// 返回一个 bool 值 表示该字段是否存在 hash 中 public static bool HashExists(string key, string hashField) { return HashExistsCompleteKey(AddSysCustomKey(key), hashField); } /// /// 判断该字段是否存在 hash 中(完整键值,不包含系统名称前缀) /// /// 全key /// hash Key /// 返回一个 bool 值 表示该字段是否存在 hash 中 public static bool HashExistsCompleteKey(string CompleteKey, string hashField) { return Db.HashExists(CompleteKey, hashField); } /// /// 从 hash 中移除指定字段 (key自动添加系统名称前缀) /// /// 原始key /// hash Key /// 返回一个 bool 值 表示从 hash 中移除指定字段 是否成功 public static bool HashDelete(string key, string hashField) { return HashDeleteCompleteKey(AddSysCustomKey(key), hashField); } /// /// 从 hash 中移除指定字段 (完整键值,不包含系统名称前缀) /// /// 全key /// hash Key /// 返回一个 bool 值 表示从 hash 中移除指定字段 是否成功 public static bool HashDeleteCompleteKey(string CompleteKey, string hashField) { return Db.HashDelete(CompleteKey, hashField); } /// /// 从 hash 中移除指定字段 批量 (key自动添加系统名称前缀) /// /// 原始key /// hash Key集合 /// 返回一个 long 值 表示 成功操作的数量 public static long HashDelete(string key, IEnumerable hashFields) { return HashDeleteCompleteKey(AddSysCustomKey(key), hashFields); } /// /// 从 hash 中移除指定字段 批量 (完整键值,不包含系统名称前缀) /// /// 全key /// hash Key集合 /// 返回一个 long 值 表示 成功操作的数量 public static long HashDeleteCompleteKey(string CompleteKey, IEnumerable hashFields) { var fields = new List(); foreach (var item in hashFields) { fields.Add(item); } return Db.HashDelete(CompleteKey, fields.ToArray()); } /// /// 在 hash 设定值 (key自动添加系统名称前缀) /// /// 原始key /// hash Key /// 值对象 /// 返回一个 bool 值 表示操作是否成功 public static bool HashSet(string key, string hashField, object value) { return HashSetCompleteKey(AddSysCustomKey(key), hashField, value); } /// /// 在 hash 设定值 (完整键值,不包含系统名称前缀) /// /// 全key /// hash Key /// 值对象 /// 返回一个 bool 值 表示操作是否成功 public static bool HashSetCompleteKey(string CompleteKey, string hashField, object value) { return Db.HashSet(CompleteKey, hashField, ConvertJson(value)); } /// /// 在 hash 中设定值 批量 (key自动添加系统名称前缀) /// /// 原始key /// key-value 字典 public static void HashSet(string key, IDictionary hashdic) { HashSetCompleteKey(AddSysCustomKey(key), hashdic); } /// /// 在 hash 中设定值 批量 (完整键值,不包含系统名称前缀) /// /// 全key /// key-value 字典 public static void HashSetCompleteKey(string CompleteKey, IDictionary hashdic) { var fields = new List(); foreach (var item in hashdic.Keys) { fields.Add(new HashEntry(item.ToSafeString(), ConvertJson(hashdic[item]))); } Db.HashSet(CompleteKey, fields.ToArray()); } /// /// 在 hash 中获取值 (key自动添加系统名称前缀) /// /// 泛型T /// 原始key /// hash Key /// 返回泛型T实例 public static T HashGet(string key, string hashField) { return HashGetCompleteKey(AddSysCustomKey(key), hashField); } /// /// 在 hash 中获取值 (完整键值,不包含系统名称前缀) /// /// 泛型T /// 全key /// hash Key /// 返回泛型T实例 public static T HashGetCompleteKey(string CompleteKey, string hashField) { string str = Db.HashGet(CompleteKey, hashField); if (!string.IsNullOrWhiteSpace(str)) { return ConvertObj(str); } return default(T); } /// /// 在 hash 中获取值集合 (key自动添加系统名称前缀) /// /// 泛型T /// 原始key /// hash Key集合 /// 返回 泛型T的 Lis 实例T集合 public static List HashGet(string key, IEnumerable hashFields) { return HashGetCompleteKey(AddSysCustomKey(key), hashFields); } /// /// 在 hash 中获取值 (完整键值,不包含系统名称前缀) /// /// 泛型T /// 全key /// hash Key集合 /// 返回 泛型T的 Lis 实例T集合 public static List HashGetCompleteKey(string CompleteKey, IEnumerable hashFields) { var fields = new List(); foreach (var item in hashFields) { fields.Add(item); } var values = Db.HashGet(CompleteKey, fields.ToArray()); return ConvetList(values); } /// /// 返回 hash 中的所有字典 (key自动添加系统名称前缀) /// /// 泛型T /// 原始key /// 返回 泛型T的 字典 实例T集合 public static Dictionary HashGetAll(string key) { return HashGetAllCompleteKey(AddSysCustomKey(key)); } /// /// 返回 hash 中的所有字典 (key自动添加系统名称前缀) /// /// 泛型T /// 全key /// 返回 泛型T的 字典 实例T集合 public static Dictionary HashGetAllCompleteKey(string CompleteKey) { var hashs = Db.HashGetAll(CompleteKey); var result = new Dictionary(); foreach (var item in hashs) { result.Add(item.Name, ConvertObj(item.Value)); } return result; } /// /// 从 hash 返回所有的字段值 (key自动添加系统名称前缀) /// /// 原始key /// 返回hash key列表 public static List HashKeys(string key) { return HashKeysCompleteKey(AddSysCustomKey(key)); } /// /// 从 hash 返回所有的字段值 (完整键值,不包含系统名称前缀) /// /// 全key /// 返回hash key列表 public static List HashKeysCompleteKey(string CompleteKey) { var keys = Db.HashKeys(CompleteKey); return keys.Select(x => x.ToString()).ToList(); } /// /// 从 hash 返回获取集合中的数量(key自动添加系统名称前缀) /// /// 原始key /// 返回一个 long 值 表示 集合中的数量 public static long HashLength(string key) { return HashLengthCompleteKey(AddSysCustomKey(key)); } /// /// 从 hash 返回获取集合中的数量(完整键值,不包含系统名称前缀) /// /// 全key /// 返回一个 long 值 表示 集合中的数量 public static long HashLengthCompleteKey(string CompleteKey) { return Db.HashLength(CompleteKey); } /// /// 返回 hash 中的所有值 (key自动添加系统名称前缀) /// /// 泛型T /// 原始key /// 返回 泛型T的 Lis 实例T集合 public static List HashValues(string key) { return HashValuesCompleteKey(AddSysCustomKey(key)); } /// /// 返回 hash 中的所有值 (完整键值,不包含系统名称前缀) /// /// 泛型T /// 全key /// 返回 泛型T的 Lis 实例T集合 public static List HashValuesCompleteKey(string CompleteKey) { var values = Db.HashValues(CompleteKey); return ConvetList(values); } #endregion #region Redis List /// /// 移除指定ListId的内部List的值 (key自动添加系统名称前缀) /// /// 泛型T /// 原始key /// 值对象 public static void ListRemove(string key, T value) { ListRemoveCompleteKey(AddSysCustomKey(key), value); } /// /// 移除指定ListId的内部List的值(完整键值,不包含系统名称前缀) /// /// 全key /// 泛型T /// 值对象 public static void ListRemoveCompleteKey(string CompleteKey, T value) { Db.ListRemove(CompleteKey, ConvertJson(value)); } /// /// 获取指定key的List(key自动添加系统名称前缀) /// /// 泛型T /// 原始key /// 返回 泛型T的 Lis 实例T集合 public static List ListRange(string key) { return ListRangeCompleteKey(AddSysCustomKey(key)); } /// /// 获取指定key的List(完整键值,不包含系统名称前缀) /// /// 泛型T /// 全key /// 返回 泛型T的 Lis 实例T集合 public static List ListRangeCompleteKey(string CompleteKey) { var values = Db.ListRange(CompleteKey); return ConvetList(values); } /// /// 入队 (key自动添加系统名称前缀) /// /// 泛型T /// 原始key /// 值对象 /// 返回一个 long 值 表示 成功操作的数量 public static long ListRightPush(string key, T value) { return ListRightPushCompleteKey(AddSysCustomKey(key), value); } /// /// 入队 (完整键值,不包含系统名称前缀) /// /// 泛型T /// 全key /// 值对象 /// 返回一个 long 值 表示 成功操作的数量 public static long ListRightPushCompleteKey(string CompleteKey, T value) { return Db.ListRightPush(CompleteKey, ConvertJson(value)); } /// /// 出队 (key自动添加系统名称前缀) /// /// 泛型T /// 原始key /// 返回泛型T实例 public static T ListRightPop(string key) { return ListRightPopCompleteKey(AddSysCustomKey(key)); } /// /// 出队(完整键值,不包含系统名称前缀) /// /// 泛型T /// 全key /// 返回泛型T实例 public static T ListRightPopCompleteKey(string CompleteKey) { string str = Db.ListRightPop(CompleteKey); if (!string.IsNullOrWhiteSpace(str)) { return ConvertObj(str); } return default(T); } /// /// 入栈 (key自动添加系统名称前缀) /// /// 泛型T /// 原始key /// 值对象 /// 返回一个 long 值 表示 成功操作的数量 public static long ListLeftPush(string key, T value) { return ListLeftPushCompleteKey(AddSysCustomKey(key), value); } /// /// 入栈 (完整键值,不包含系统名称前缀) /// /// 泛型T /// 全key /// 值对象 /// 返回一个 long 值 表示 成功操作的数量 public static long ListLeftPushCompleteKey(string CompleteKey, T value) { return Db.ListLeftPush(CompleteKey, ConvertJson(value)); } /// /// 出栈(key自动添加系统名称前缀) /// /// 泛型T /// 原始key /// 返回泛型T实例 public static T ListLeftPop(string key) { return ListLeftPopCompleteKey(AddSysCustomKey(key)); } /// /// 出栈(完整键值,不包含系统名称前缀) /// /// 泛型T /// 全key /// 返回泛型T实例 public static T ListLeftPopCompleteKey(string CompleteKey) { string str = Db.ListLeftPop(CompleteKey); if (!string.IsNullOrWhiteSpace(str)) { return ConvertObj(str); } return default(T); } /// /// 获取集合中的数量(key自动添加系统名称前缀) /// /// 原始key /// 返回一个 long 值 表示 集合中的数量 public static long ListLength(string key) { return ListLengthCompleteKey(AddSysCustomKey(key)); } /// /// 获取集合中的数量(完整键值,不包含系统名称前缀) /// /// 全key /// 返回一个 long 值 表示 集合中的数量 public static long ListLengthCompleteKey(string CompleteKey) { return Db.ListLength(CompleteKey); } #endregion #region Redis SortedSet /// /// SortedSet 新增 (key自动添加系统名称前缀) /// /// 原始key /// 成员 /// 分数 /// 返回一个 bool 值 表示操作是否成功 public static bool SortedSetAdd(string key, object member, double score) { return SortedSetAddCompleteKey(AddSysCustomKey(key), member, score); } /// /// SortedSet 新增 (完整键值,不包含系统名称前缀) /// /// 全key /// 成员 /// 分数 /// 返回一个 bool 值 表示操作是否成功 public static bool SortedSetAddCompleteKey(string CompleteKey, object member, double score) { return Db.SortedSetAdd(CompleteKey, ConvertJson(member), score); } /// /// 在有序集合中返回指定范围的元素,默认情况下从低到高。 (key自动添加系统名称前缀) /// /// 泛型T /// 原始key /// 开始条目 /// 结束条目 /// 排序类型 0Ascending 升序 1Descending降序 /// 返回 泛型T的 Lis 实例T集合 public static List SortedSetRangeByRank(string key, long start = 0L, long stop = -1L, int order = 0) { return SortedSetRangeByRankCompleteKey(AddSysCustomKey(key), start, stop, order); } /// /// 在有序集合中返回指定范围的元素,默认情况下从低到高。 (完整键值,不包含系统名称前缀) /// /// 泛型T /// 全key /// 开始条目 /// 结束条目 /// 排序类型 0Ascending 升序 1Descending降序 /// 返回 泛型T的 Lis 实例T集合 public static List SortedSetRangeByRankCompleteKey(string CompleteKey, long start = 0L, long stop = -1L, int order = 0) { var values = Db.SortedSetRangeByRank(CompleteKey, start, stop, (Order)order); return ConvetList(values); } /// /// 返回有序集合的元素个数 (key自动添加系统名称前缀) /// /// 原始key /// 返回一个 long 值 表示 集合中的数量 public static long SortedSetLength(string key) { return SortedSetLengthCompleteKey(AddSysCustomKey(key)); } /// /// 返回有序集合的元素个数 (完整键值,不包含系统名称前缀) /// /// 全key /// 返回一个 long 值 表示 集合中的数量 public static long SortedSetLengthCompleteKey(string CompleteKey) { return Db.SortedSetLength(CompleteKey); } /// /// 移除集合的元素(key自动添加系统名称前缀) /// /// 原始key /// 成员 /// 返回一个 bool 值 表示操作是否成功 public static bool SortedSetRemove(string key, object memebr) { return SortedSetRemoveCompleteKey(AddSysCustomKey(key), memebr); } /// /// 移除集合的元素(完整键值,不包含系统名称前缀) /// /// 全key /// 成员 /// 返回一个 bool 值 表示操作是否成功 public static bool SortedSetRemoveCompleteKey(string CompleteKey, object memebr) { return Db.SortedSetRemove(CompleteKey, ConvertJson(memebr)); } /// /// 增量的得分排序的集合中的成员存储键值键按增量 (key自动添加系统名称前缀) /// /// 原始key /// 成员 /// /// public static double SortedSetIncrement(string key, object member, double value = 1) { return SortedSetIncrementCompleteKey(AddSysCustomKey(key), member, value); } /// /// 增量的得分排序的集合中的成员存储键值键按增量 (完整键值,不包含系统名称前缀) /// /// 全key /// 成员 /// /// public static double SortedSetIncrementCompleteKey(string CompleteKey, object member, double value = 1) { return Db.SortedSetIncrement(CompleteKey, ConvertJson(member), value); } #endregion #region Redis 订阅 /// /// Redis发布订阅 订阅 (channel自动添加系统名称前缀) /// /// 泛型T /// 订阅通道 /// 处理委托方法 public static void Subscribe(string channel, Action handler = null) { SubscribeComplete(AddSysCustomKey(channel), handler); } /// /// Redis发布订阅 订阅 (完整键值,不包含系统名称前缀) /// /// 泛型T /// 订阅通道 包含系统前缀 /// 处理委托方法 public static void SubscribeComplete(string CompleteChannel, Action handler = null) { var sub = Client.GetSubscriber(); sub.Subscribe(CompleteChannel, (channel, message) => { if (handler == null) { Console.WriteLine(CompleteChannel + " 订阅收到消息:" + message); } else { string valuse = message; handler(channel, ConvertObj(valuse)); } }); } /// /// Redis发布订阅 发布 (channel自动添加系统名称前缀) /// /// 订阅通道 /// 消息实例 /// 返回一个 long 值 表示 成功操作的数量 public static long Publish(string channel, object msg) { return PublishComplete(AddSysCustomKey(channel), ConvertJson(msg)); } /// /// Redis发布订阅 发布 (完整键值,不包含系统名称前缀) /// /// 订阅通道 /// 消息实例 /// 返回一个 long 值 表示 成功操作的数量 public static long PublishComplete(string CompleteChannel, object msg) { var sub = Client.GetSubscriber(); return sub.Publish(CompleteChannel, ConvertJson(msg)); } /// /// Redis发布订阅 取消订阅 (channel自动添加系统名称前缀) /// /// 订阅通道 public static void Unsubscribe(string channel) { UnsubscribeComplete(AddSysCustomKey(channel)); } /// /// Redis发布订阅 取消订阅 (完整键值,不包含系统名称前缀) /// /// 订阅通道 public static void UnsubscribeComplete(string CompleteChannel) { var sub = Client.GetSubscriber(); sub.Unsubscribe(CompleteChannel); } /// /// Redis发布订阅 取消全部订阅 /// public static void UnsubscribeAll() { var sub = Client.GetSubscriber(); sub.UnsubscribeAll(); } #endregion #region 建值管理 /// /// 检查redis key建值,根据键值 (key自动添加系统名称前缀) /// /// 原始key /// 返回一个 bool 值 表示该建值是否存在 hash 中 public static bool CheckKey(string key) { return CheckKeyCompleteKey(AddSysCustomKey(key)); } /// /// 检查redis key建值,根据键值 (完整键值,不包含系统名称前缀) /// /// 全key /// 返回一个 bool 值 表示该建值是否存在 hash 中 public static bool CheckKeyCompleteKey(string CompleteKey) { return Db.KeyExists(CompleteKey); } /// /// 获取redis据键值列表,只获取本系统的系统前缀名称 /// /// 返回键值列表 public static List GetAllKey() { List list = new List(); foreach (var item in Client.GetEndPoints()) { var server = Client.GetServer(item); var temp = server.Keys(0, "*").Select(d => d.ToString()).Where(x => x.StartsWith(systemKey)).ToList(); list.AddRange(temp); } return list; } #endregion #region 移除键值 /// /// 移除redis键值,根据键值 (key自动添加系统名称前缀) /// /// 原始key /// 返回一个 bool 值 表示操作是否成功 public static bool RemoveKey(string key) { return RemoveKeyCompleteKey(AddSysCustomKey(key)); } //批量删除key,用于一些批量任务的场合,比如同步任务。 //不管有没有,都删除。 //redis的文档说,如果没有key,删除了也不会报错。 //所以永远返回true public static bool RemoveKeyList(List keylist) { //给每一个key,添加前缀。 List preNameList = new List(); foreach (var item in keylist) { preNameList.Add(AddSysCustomKey(item)); } RemoveKeyCompleteKeyList(preNameList); return true; } /// /// 移除redis键值,根据键值 (完整键值,不包含系统名称前缀) /// /// 全key /// 返回一个 bool 值 表示操作是否成功 public static bool RemoveKeyCompleteKey(string CompleteKey) { if (!Db.KeyExists(CompleteKey)) return true; return Db.KeyDelete(CompleteKey); } //批量删除key,用于一些批量任务的场合,比如同步任务。 //不管有没有,都删除。 //redis的文档说,如果没有key,删除了也不会报错。 //所以永远返回true public static bool RemoveKeyCompleteKeyList(List CompleteKey) { //将字符串列表,转换成 RedisKey 数组 RedisKey[] arrKeys = new RedisKey[CompleteKey.Count]; int i = 0; foreach(var p in CompleteKey) { arrKeys[i] = (RedisKey)p; //RedisKey类型支持从字符串类型的隐式转换 i++; } //调用redis的批量删除功能。 long affectkeys = Db.KeyDelete(arrKeys); return true; } /// /// 清空所有指定前缀参数集合键值 (key自动添加系统名称前缀) /// /// 原始key /// 返回一个 long 值 表示 成功操作的数量 public static long ClearAllStartsWithKey(string key = "") { long count = 0; foreach (var item in GetAllKey()) { if (item.StartsWith(AddSysCustomKey(key))) { if (Db.KeyDelete(item)) count++; } } return count; } /// /// 清空所有键值 /// /// 返回一个 long 值 表示 成功操作的数量 public static long ClearAllKey() { long count = 0; foreach (var item in GetAllKey()) { if (Db.KeyDelete(item)) count++; } return count; } #endregion } }