How do you handle failed redis connections

I am using the Redis Windows implementation with the StackExchange.Redis client. My question is how do you handle reconnection attempts if the original connection fails. I think of the worst case scenario when all Redis masters and subordinate services are omitted. The problem is that every time my application needs something from the cache, it will try to connect to Redis (if the connection is not successful), and this is very time-consuming. My factory class is as follows:

 private ConnectionMultiplexer GetConnection()
        {

            if (connection != null && connection.IsConnected) return connection;

            lock (_lock)
            {
                if (connection != null && connection.IsConnected) return connection;

                if (connection != null)
                {
                    logger.Log("Redis connection disconnected. Disposing connection...");
                    connection.Dispose();
                }

                logger.Log("Creating new instance of Redis Connection");


                connection = ConnectionMultiplexer.Connect(connectionString.Value);
            }

            return connection;

        }

        public IDatabase Database(int? db = null)
        {
            try
            {
                return !redisConnectionValid ? null : GetConnection().GetDatabase(db ?? settings.DefaultDb);
            }
            catch (Exception ex)
            {
                redisConnectionValid = false;
                logger.Log(Level.Error, String.Format("Unable to create Redis connection: {0}", ex.Message));
                return null;
            }
        }

, singleton . , (redisConnectionValid), ( 5-10 ). , ? - , Redis . , - Redis, /- .

+4
1

StackExchange.Redis , IsConnected. , :

private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() => {
    return ConnectionMultiplexer.Connect("mycache.redis.cache.windows.net,abortConnect=false,ssl=true,password=...");
});

public static ConnectionMultiplexer Connection {
    get {
        return lazyConnection.Value;
    }
}

, "abortConnect" "false". , , ConnectionMultiplexer .

+16

All Articles