StackExchange.Redis 有多个客户端名称
StackExchange.Redis with multiple client names
我们需要使用带有 StackExchange.Redis 的多个客户端名称,据我所知,这意味着多个连接字符串和 ConnectionMultiplexer
.
的多个(静态)实例
我目前的想法是创建一个静态包装器 class 并使用以客户端名称(或整个连接字符串)为键的私有字典来存储多路复用器实例,并公开一个 GetDatabase(name)
查找多路复用器(或锁定并创建它)的方法和 returns GetDatabase()
对实例调用调用者的结果。
这是我首先想到的,但如果有更好的方法来处理这个要求,我也不会感到惊讶。
我过去遇到过同样的情况,我需要根据配置动态更改连接。为了克服这个问题,我创建了静态 Helper
class,它将端点 IP 地址作为输入,并将 returns 连接作为结果。
/// <summary>
/// Helper class for connection with Redis Server.
/// </summary>
public static class Helper
{
/// <summary>
/// Configuration option to connect with Redis.
/// </summary>
private static Lazy<ConfigurationOptions> configOptions(string ipAddress)
{
var configOptions = new ConfigurationOptions();
configOptions.EndPoints.Add(ipAddress);
/*
...Other Configurations...
*/
return new Lazy<ConfigurationOptions>(() => configOptions);
}
private static Lazy<ConnectionMultiplexer> lazyConnection(string ipAddress)
{
return new Lazy<ConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(configOptions(ipAddress).Value));
}
/// <summary>
/// Connection property to connect Redis.
/// </summary>
public static ConnectionMultiplexer Connection(string ipAddress)
{
return lazyConnection(ipAddress).Value;
}
}
如何使用:
var database = Helper.Connection("Your IP address").GetDatabase(0);
这是简单的解决方法,当然,您可以根据需要对其进行修改并使其更具可配置性。这里的想法是让 Redis 连接动态化,这样我们就可以基于它执行其他操作,比如设置和获取键和值。
我们需要使用带有 StackExchange.Redis 的多个客户端名称,据我所知,这意味着多个连接字符串和 ConnectionMultiplexer
.
我目前的想法是创建一个静态包装器 class 并使用以客户端名称(或整个连接字符串)为键的私有字典来存储多路复用器实例,并公开一个 GetDatabase(name)
查找多路复用器(或锁定并创建它)的方法和 returns GetDatabase()
对实例调用调用者的结果。
这是我首先想到的,但如果有更好的方法来处理这个要求,我也不会感到惊讶。
我过去遇到过同样的情况,我需要根据配置动态更改连接。为了克服这个问题,我创建了静态 Helper
class,它将端点 IP 地址作为输入,并将 returns 连接作为结果。
/// <summary>
/// Helper class for connection with Redis Server.
/// </summary>
public static class Helper
{
/// <summary>
/// Configuration option to connect with Redis.
/// </summary>
private static Lazy<ConfigurationOptions> configOptions(string ipAddress)
{
var configOptions = new ConfigurationOptions();
configOptions.EndPoints.Add(ipAddress);
/*
...Other Configurations...
*/
return new Lazy<ConfigurationOptions>(() => configOptions);
}
private static Lazy<ConnectionMultiplexer> lazyConnection(string ipAddress)
{
return new Lazy<ConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(configOptions(ipAddress).Value));
}
/// <summary>
/// Connection property to connect Redis.
/// </summary>
public static ConnectionMultiplexer Connection(string ipAddress)
{
return lazyConnection(ipAddress).Value;
}
}
如何使用:
var database = Helper.Connection("Your IP address").GetDatabase(0);
这是简单的解决方法,当然,您可以根据需要对其进行修改并使其更具可配置性。这里的想法是让 Redis 连接动态化,这样我们就可以基于它执行其他操作,比如设置和获取键和值。