using FreeRedis;
using System;
using System.Collections.Generic;
using System.Linq;
namespace WCS.Core.Redis
{
///
/// Redis操作类
///
public class RedisHelper
{
///
/// 连接集合
///
private static List RedisClients = new List();
///
/// 默认上下文类类型
///
public static string DefaultDbContextType { get; private set; } = null!;
///
/// 设置默认链接
///
///
public static void SetDefaultDbContextType(string key)
{
DefaultDbContextType = key;
}
///
/// 默认链接
///
public static RedisClient Default
{
get
{
{
if (DefaultDbContextType == null)
throw new Exception("请先设置默认RedisDB库,调用静态方法SetDefaultDbContextType()");
return Context(DefaultDbContextType);
}
}
}
///
/// 创建一个连接
///
/// 连接字符串
/// 标识
/// 是否为默认连接,默认为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)
{
SetDefaultDbContextType(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;
}
}
///
/// 链接集合
///
public class RedisClientList
{
///
/// 连接集合
///
/// 连接标识
/// 连接
/// 连接字符串
public RedisClientList(string key, RedisClient client, string connectionConfig)
{
Key = key;
Client = client;
ConnectionConfig = connectionConfig;
}
///
/// 连接标识
///
public string Key { get; set; }
///
/// 连接
///
public RedisClient Client { get; set; }
///
/// 连接字符串
///
public string ConnectionConfig { get; set; }
}
}