123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109 |
- using FreeRedis;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- namespace WCS.Redis
- {
- /// <summary>
- /// Redis操作类
- /// </summary>
- public class RedisHelper
- {
- /// <summary>
- /// 连接集合
- /// </summary>
- private static List<RedisClientList> RedisClients = new List<RedisClientList>();
- /// <summary>
- /// 默认上下文类类型
- /// </summary>
- public static string DefaultDbContextType { get; private set; } = null!;
- /// <summary>
- /// 设置默认链接
- /// </summary>
- /// <param name="key"></param>
- public static void SetDefaultDbContextType(string key)
- {
- DefaultDbContextType = key;
- }
- /// <summary>
- /// 默认链接
- /// </summary>
- public static RedisClient Default()
- {
- if (DefaultDbContextType == null)
- throw new Exception("请先设置默认RedisDB库,调用静态方法SetDefaultDbContextType()");
- return Context(DefaultDbContextType);
- }
- /// <summary>
- /// 创建一个连接
- /// </summary>
- /// <param name="connectionString"> 连接字符串</param>
- /// <param name="key">标识</param>
- /// <param name="defaultClient"> 是否为默认连接,默认为false</param>
- /// <returns></returns>
- 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)
- {
- SetDefaultDbContextType(key);
- }
- return ctx.Client;
- }
- /// <summary>
- /// 获取指定的连接
- /// </summary>
- /// <param name="key"></param>
- /// <returns></returns>
- /// <exception cref="Exception"></exception>
- public static RedisClient Context(string key)
- {
- var ctx = RedisClients.FirstOrDefault(v => v.Key == key);
- if (ctx == null) throw new Exception("没有对应的链接,请先调用创建");
- return ctx.Client;
- }
- }
- /// <summary>
- /// 链接集合
- /// </summary>
- public class RedisClientList
- {
- /// <summary>
- /// 连接集合
- /// </summary>
- /// <param name="key">连接标识</param>
- /// <param name="client">连接</param>
- /// <param name="connectionConfig">连接字符串</param>
- public RedisClientList(string key, RedisClient client, string connectionConfig)
- {
- this.Key = key;
- Client = client;
- ConnectionConfig = connectionConfig;
- }
- /// <summary>
- /// 连接标识
- /// </summary>
- public string Key { get; set; }
- /// <summary>
- /// 连接
- /// </summary>
- public RedisClient Client { get; set; }
- /// <summary>
- /// 连接字符串
- /// </summary>
- public string ConnectionConfig { get; set; }
- }
- }
|