Myl*_*s J 5 redis stackexchange.redis
我正在与StackExchange.Redis客户端一起使用Redis Windows实现.我的问题是,如果初始连接失败,如何处理重新连接尝试.我正在考虑所有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;
}
}
Run Code Online (Sandbox Code Playgroud)
您可以看到我使用单例模式来创建连接.如果初始连接失败,我将设置一个标志(redisConnectionValid),以防止后续调用尝试重新创建连接(大约需要5-10秒).有比这更好的方法吗?我们的设计目标是让我们的应用程序正常工作,即使Redis缓存不可用.我们不希望应用程序性能受到影响,因为连续的Redis连接尝试最终会在最坏的情况下失败/超时.
Mik*_*der 17
您应该让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;
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,"abortConnect"设置为"false".这意味着如果第一次连接尝试失败,ConnectionMultiplexer将在后台重试,而不是抛出异常.
| 归档时间: |
|
| 查看次数: |
8178 次 |
| 最近记录: |