我正在使用Redis Windows实现和StackExchange.Redis客户端。我的问题是,如果初始连接失败,您如何处理重新连接尝试。我在考虑最坏的情况,当所有Redis的主从服务都关闭了。问题是,每当我的应用程序需要缓存中的内容时,它都会尝试重新连接到Redis (如果初始连接失败),这非常耗时。我的工厂类看起来像这样:
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;
}
}您可以看到,我正在使用单例模式来创建连接。如果初始连接失败,我将设置一个标志(redisConnectionValid),以防止后续调用尝试重新创建连接(这大约需要5-10秒)。还有比这更好的方法吗?我们的设计目标是让我们的应用程序正常工作,即使Redis缓存不可用。我们不希望应用程序的性能因为连续的Redis连接尝试而受到影响,在最坏的情况下最终会失败/超时。
发布于 2014-11-25 03:59:41
您应该让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将在后台重试,而不是抛出异常。
https://stackoverflow.com/questions/27102351
复制相似问题