簡體   English   中英

多個Redis服務器的.NET Core StackExchange.Redis ConnectionMultiplexer設置

[英].NET Core StackExchange.Redis ConnectionMultiplexer setup for multiple redis servers

我正在.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");

密鑰按預期存儲在服務器1的Redis存儲中。


現在,我需要集成第二個存儲。

可以使用ConnectionMultiplexer連接到兩個服務器嗎?

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

如何獲得指向正確的服務器(第一個或第二個)的正確數據庫?

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

而在啟動

services.AddSingleton<IOtherStorage>(c => new OtherStorage("server2:6279");

或者只是擁有一個ConnectionMultiplexer工廠的Singleton:

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();

....

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM