Safely reinitialising the multiplexer after network failure
We identified that if we receive RedisConnectionException with failure types of SocketFailure or SocketClosed, the multiplexer no longer works and we need to reinstantiate it.
This is tricky, because we could be in the middle of servicing many requests, and we want a singleton instance. As such, we've wrapped the calling code in a critical section, and tried to determine whether the connection has happened by another caller by looking at the IsConnected property.
A bit like this (we've taken some Lazy type optimisations out for clarity);
if (_connection != null &&_connection.IsConnected) return;
lock (_lock)
{
if (_connection == null || _connection.IsConnected == false)
{
_connection?.Dispose();
_connection = return ConnectionMultiplexer.Connect(_options);
}
}
However, we are still getting race conditions - which is if the lock is released and the next caller enters and makes the IsConnected check whilst the multiplexer is 'Connecting'.
There doesn't seem to be a way to directly determine that the servers are actually not yet connected. I note in PhysicalBridge.State has the following values Connecting, ConnectedEstablishing and ConnectedEstablished.
Is it feasible for us to find out these states, so we can change our logic to somthing like;
if (_connection != null &&_connection.IsConnected) return;
lock (_lock)
{
if (_connection == null || (_connection.IsConnected == false || _connection.IsConnecting == false))
{
_connection?.Dispose();
_connection = return ConnectionMultiplexer.Connect(_options);
}
}
I'm happy to submit a PR for a IsConnecting method or similar on ConnectionMultiplexer, or take advice on better options :)
Thanks
Richard
Added in #803, thanks again for the contribution!