Reputation: 33783
Basically, I have a "DON'T DO THIS" Sentinel scenario. Because Sentinel is not safe in such scenario, I've implemented the following
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");
}
}
};
So, when my main connection is down, I change the configuration, by calling (src as ConnectionMultiplexer).Configure(writer), so that ConnectionMultiplexer can use the new configuration. However, ConnectionMultiplexer continue to use the old one.
Question: How can I change ConnectionMultiplexer.configuration in the ConnectionFailed event ?
Upvotes: 3
Views: 2975
Reputation: 558
I looked at the source code of the library, it seems there is no desired functionality. There is internal method Reconfigure, but it tries to connect to other servers from the configuration.
I would suggest you to refactor, if your application is not very large. Make a wrapper over ConnectionMultiplexer, pass wrapper to objects where the connection is used. We do wrap method GetConnection, which returns all the links on a single object. All who need the connection will call this method, no needs to store connection. Inside the wrapper OnFailed subscribe to an event handler to create a new connection to a Backup.
Upvotes: 2
Reputation: 2453
Not sure if that would be acceptable, not exactly switching the config but more like rebuilding the multiplixer
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);
}
Upvotes: 0