.NET Core StackExchange.Redis ConnectionMultiplexer 设置多个 Redis 服务器

mon*_*nty 5 c# redis stackexchange.redis .net-core

我正在 .NET Core 2.2 中开发一些 Web api

这些需求使我们达到了在多个 Redis 存储中存储/缓存/集中数据的地步(为了简单起见,我们假设有 2 个 Redis 服务器)。

那将是(例如)

  1. 服务器1用于数据保护
  2. 服务器2用于一些其他数据

到目前为止,数据保护似乎有效,并且按照基本使用指南中的建议,使用连接多路复用器(预先将其添加为单例以供重用)进行配置。

StartUp.ConfigureServices的相关部分

  ConnectionMultiplexer cm = ConnectionMultiplexer.Connect("server1:6729");
  services.AddSingleton<IConnectionMultiplexer>(cm);

  services.AddDataProtection()
    .SetApplicationName("myapp")
    .PersitKeysToStackExchangeRedis(cm, "DataProtection-Keys");
Run Code Online (Sandbox Code Playgroud)

密钥按预期存储在服务器 1 上的 Redis 存储中。


现在我需要集成第二个存储。

ConnectionMultiplexer 可以用来连接两台服务器吗?

ConnectionMultiplexer cm = ConnectionMultiplexer.Connect("server1:6729;server2:6729"); //?
Run Code Online (Sandbox Code Playgroud)

如何获得指向正确(第一或第二)服务器的正确数据库?

the*_*000 6

或者只是有一个ConnectionMultiplexer工厂的单例:

public class ConnectionFactory
{
    private Lazy<ConnectionMultiplexer> _cnn1 { get; set; }
    private Lazy<ConnectionMultiplexer> _cnn2 { get; set;}
    public ConnectionFactory(string cnn1, string cnn2)
    {
        _cnn1 = new Lazy<UserQuery.ConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(cnn1));
        _cnn2 = new Lazy<UserQuery.ConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(cnn2));
    }
    public ConnectionMultiplexer GetConnection1()
    {
        return _cnn1.Value;
    }
    public ConnectionMultiplexer GetConnection2()
    {
        return _cnn2.Value;
    }
}
Run Code Online (Sandbox Code Playgroud)

并注册如下:

var factory = new ConnectionFactory("server1:6379", "server2:6379");
services.AddSingleton(factory);

var cm1 = factory.GetConnection1();
var cm2 = factory.GetConnection2();

....
Run Code Online (Sandbox Code Playgroud)


ste*_*-fu 3

ConnectionMultiplexer 可以连接到服务器集群,但这仅用于同一数据集的故障转移/负载平衡/复制。

如果您只想对键进行逻辑分离,Redis 内部有 8 个数据库。您拥有其他存储代码,只需调用即可,_muxer.GetDatabase(3)例如,您可以使用同一服务器。

如果您有其他原因想要单独的服务器,我会创建一个不同的包装类/接口。包装类可以新建一个ConnectionMultiplexer并注入到 Singleton 范围中。您最终会拥有 2 个多路复用器实例,但这不是一个大问题,要避免的主要问题是更新大量实例,例如每次调用。

public Interface IOtherStorage
{
    void StoreItem(string key, string value);
}

public class OtherStorage : IOtherStorage
{
    private IConnectionMultiplexer _muxer;

    public OtherStorage(string connection)
    {
        _muxer = ConnectionMultiplexer.Connection(connection)
    }

    public void StoreItem(string key, string value)
    {
        _muxer.GetDatabase().StringSet(key, value);
    }
}
Run Code Online (Sandbox Code Playgroud)

并且在启动时

services.AddSingleton<IOtherStorage>(c => new OtherStorage("server2:6279");
Run Code Online (Sandbox Code Playgroud)