using FreeRedis; namespace ServiceCenter.Redis { /// /// Redis /// public static class RedisHub { /// /// 连接集合 /// private static List RedisClients = new List(); /// /// 默认上下文类类型 /// public static string DefaultContextType { get; private set; } = null!; /// /// 默认监控上下文类类型 /// public static string MonitorContextType { get; private set; } = null!; /// /// 默认调试上下文类类型 /// public static string DebugContextType { get; private set; } = null!; /// /// 设置默认链接 /// /// public static void SetDefaultContextType(string key) { DefaultContextType = key; } /// /// 设置监控链接 /// /// public static void SetMonitorContextType(string key) { MonitorContextType = key; } /// /// 设置监控链接 /// /// public static void SetDebugContextType(string key) { DebugContextType = key; } /// /// 默认链接 /// public static RedisClient Default { get { { if (DefaultContextType == null) throw new Exception("请先设置默认RedisDB库,调用静态方法SetDefaultDbContextType()"); return Context(DefaultContextType); } } } /// /// 监控连接 /// public static RedisClient Monitor { get { { if (MonitorContextType == null) throw new Exception("请先设置监控RedisDB库,调用静态方法SetMonitorContextType()"); return Context(MonitorContextType); } } } /// /// 监控连接 /// public static RedisClient Debug { get { { if (MonitorContextType == null) throw new Exception("请先设置DebugRedisDB库,调用静态方法SetDebugContextType()"); return Context(MonitorContextType); } } } /// /// 创建一个连接 /// /// 连接字符串 /// 标识 /// 是否为默认连接,默认为false /// public static RedisClient CreateContext(string connectionString, string key, bool defaultClient = false) { var ctx = RedisClients.FirstOrDefault(v => v.Key == key); if (ctx != null) return ctx.Client; ctx = new RedisClientList(key, new RedisClient(connectionString), connectionString); RedisClients.Add(ctx); if (defaultClient) { SetDefaultContextType(key); } return ctx.Client; } /// /// 获取指定的连接 /// /// /// /// public static RedisClient Context(string key) { var ctx = RedisClients.FirstOrDefault(v => v.Key == key); if (ctx == null) throw new Exception("没有对应的链接,请先调用创建"); return ctx.Client; } /// /// 检查Redis中是否有对应key且value不为空 /// /// redis连接 /// 要检查的Key /// /// 1.key不存在,创建这个key value默认为三个空格符。返回null /// 2.key存在单value为空 返回null /// 3.key存在value不为空 返回获取到的值 /// public static string? Check(this RedisClient redisClient, string key) { var result = redisClient.Get(key); if (!string.IsNullOrEmpty(result)) return result; redisClient.Set(key, " "); return null; } } }