基本上,我有一个"DON'T DO THIS" Sentinel场景。因为Sentinel在这种情况下不安全,所以我实现了以下
var main = "192.168.XXX.YY:6379,abortConnect=false";
var backup = "192.168.XXX.YY:6379,abortConnect=false";
IConnectionMultiplexer redis = ConnectionMultiplexer.Connect(main);
redis.ConnectionFailed += (src, args) =>
{
if ((src as ConnectionMultiplexer).Configuration != backup) {
using (var writer = new StringWriter()) {
writer.Write(backup);
(src as ConnectionMultiplexer).Configure(writer);
/**
* Just for checking. It does not save
**/
(src as ConnectionMultiplexer).GetDatabase().StringSet("aaa", "bbb");
}
}
};
因此,当我的主连接断开时,我通过调用(src作为ConnectionMultiplexer).Configure(writer)来更改配置,以便ConnectionMultiplexer可以使用新配置。但是,ConnectionMultiplexer继续使用旧的。
问题:如何在ConnectionFailed事件中更改ConnectionMultiplexer.configuration?
答案 0 :(得分:2)
我查看了库的source code,似乎没有所需的功能。有内部方法重新配置,但它尝试从配置连接到其他服务器。
如果你的申请不是很大,我建议你重构一下。在ConnectionMultiplexer上创建一个包装器,将包装器传递给使用连接的对象。我们做了包装方法GetConnection,它返回单个对象上的所有链接。所有需要连接的人都会调用此方法,无需存储连接。在包装器内部OnFailed订阅事件处理程序以创建与备份的新连接。
答案 1 :(得分:0)
不确定这是否可以接受,不完全切换配置,更像是重建多路复用器
private static Lazy<IConnectionMultiplexer> _redisMux = new Lazy<ConnectionMultiplexer>(CreateMultiplexer);
public static IConnectionMultiplexer Multiplexer { get { return _redisMux.Value; } }
private const string Main = "192.168.XXX.YY:6379,abortConnect=false";
private const string Backup = "192.168.XXX.YY:6379,abortConnect=false";
private static string ActiveConfig = Main;
private static ConnectionMultiplexer CreateMultiplexer()
{
var mux = ConnectionMultiplexer.Connect(ActiveConfig));
mux.ConnectionFailed += OnConnectionFailed;
return mux;
}
[MethodImpl(MethodImplOptions.Synchronized)]
private static void OnConnectionFailed(object sender, ConnectionFailedEventArgs e)
{
ActiveConfig = Backup;
try { Multiplexer.Dispose(); } catch { }
_redisMux = new Lazy<ConnectionMultiplexer>(CreateMultiplexer);
}