gpt4 book ai didi

c# - .NET Core StackExchange.Redis ConnectionMultiplexer 设置多个 redis 服务器

转载 作者:IT王子 更新时间:2023-10-29 06:16:28 24 4
gpt4 key购买 nike

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

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

那将是(例如)

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

到目前为止,数据保护似乎有效,并且按照 basic usage guide 中的建议使用连接多路复用器进行配置(之前添加为单例以供重用) .

StartUp.ConfigureServices相关部分

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

services.AddDataProtection()
.SetApplicationName("myapp")
.PersitKeysToStackExchangeRedis(cm, "DataProtection-Keys");

key 按预期存储在服务器 1 的 redis 存储中。


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

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

ConnectionMultiplexer cm = ConnectionMultiplexer.Connect("server1:6729;server2:6729"); //?

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

最佳答案

或者只是有一个 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;
}
}

然后像这样注册:

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

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

....

关于c# - .NET Core StackExchange.Redis ConnectionMultiplexer 设置多个 redis 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54767766/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com