简体   繁体   English

具有多个客户端名称的 StackExchange.Redis

[英]StackExchange.Redis with multiple client names

We have a need to use multiple client names with StackExchange.Redis, which as far as I can tell means multiple connection strings and multiple (static) instances of ConnectionMultiplexer .我们需要在 StackExchange.Redis 中使用多个客户端名称,据我所知,这意味着多个连接字符串和ConnectionMultiplexer多个(静态)实例。

My current thinking is to create a static wrapper class and use a private dictionary keyed by client name (or the whole connection string) to store the multiplexer instances, and expose a single GetDatabase(name) method which looks up the multiplexer (or locks and creates it) and returns the result of the GetDatabase() call on the instance to the caller.我目前的想法是创建一个静态的包装类,并使用客户端名称键入专用词典(或整个连接字符串)来存储多路复用器实例,并公开一个GetDatabase(name)其中查找多路复用方法(或锁,创建它)并将对实例的GetDatabase()调用的结果返回给调用者。

This was the first thing I thought of, but I wouldn't be surprised if there were a better way to handle this requirement.这是我想到的第一件事,但如果有更好的方法来处理这个需求,我不会感到惊讶。

I faced the same situation in the past in which I need to change the connection dynamically based on the configuration.我过去遇到过同样的情况,需要根据配置动态更改连接。 To overcome that I have created static Helper class which takes endpoint IP address as input and returns connection as result.为了克服这个问题,我创建了静态Helper类,它将端点 IP 地址作为输入并返回连接作为结果。

/// <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;
    }
}

How to use this:如何使用这个:

var database = Helper.Connection("Your IP address").GetDatabase(0);

This is the simple workaround, of course, you can modify it as per your need and make it more configurable.这是一个简单的解决方法,当然,您可以根据需要修改它并使其更具可配置性。 The idea here is to make Redis connection dynamic so that we can perform other operation based on that, like setting and getting keys and values.这里的想法是使 Redis 连接动态化,以便我们可以基于此执行其他操作,例如设置和获取键和值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM