【发布时间】:2019-10-02 06:10:30
【问题描述】:
我正在使用 Azure Redis 缓存进行开发,并想验证我处理异常的方式。根据最佳实践,可能会遇到 RedisConnectionExceptions,为了解决这个问题,我们必须处理旧的 ConnectionMultiplexer 并创建一个新的。如果 abortConnect 设置为 false,则多路复用器将静默重试连接而不会引发错误。因此,如果抛出异常,它只会在尝试重新连接并且仍然失败之后。我对此的理解正确吗? 这是我的连接字符串 -
cachename.redis.cache.windows.net:6380,password=Password,ssl=True,abortConnect=False
我相信只有当您尝试在多路复用器上调用 GetConnection() 时才会发生连接异常。在下面找到我的代码 -
static Lazy<ConnectionMultiplexer> multiplexer = CreateMultiplexer();
public static ConnectionMultiplexer GetConnection() => multiplexer.Value;
private static Lazy<ConnectionMultiplexer> CreateMultiplexer()
{
return new Lazy<ConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(connectionString));
}
private static void CloseMultiplexer(Lazy<ConnectionMultiplexer> oldMultiplexer)
{
if (oldMultiplexer != null)
{
oldMultiplexer.Value.Close();
}
}
public static void Reconnect()
{
var oldMultiplexer = multiplexer;
CloseMultiplexer(multiplexer);
multiplexer = CreateMultiplexer();
}
我在下面的另一个课程中使用这个 -
public class RedisCacheManager
{
private static IDatabase _cache;
private TimeSpan expiry = new TimeSpan(hours: 6, minutes: 0, seconds: 0);
public RedisCacheManager()
{
try
{
_cache = RedisCacheHelper.GetConnection().GetDatabase();
}
catch(RedisConnectionException)
{
RedisCacheHelper.Reconnect();
new RedisCacheManager();
}
}
public async Task<RedisValue[]> GetFromCacheAsync(List<string> keys)
{
var cacheValues = await _cache.StringGetAsync(keys.Select(k => (RedisKey)k).ToArray());
return cacheValues;
}
public async Task SaveInCacheAsync<TValue>(Dictionary<string, TValue> kvps)
{
var tasks = new List<Task>();
foreach(var kvp in kvps)
{
tasks.Add(_cache.StringSetAsync(kvp.Key, JsonConvert.SerializeObject(kvp), expiry));
}
await Task.WhenAll(tasks);
}
}
我不确定在 catch 块中调用构造函数是一个好习惯。在调用 StringGetAsync 和 StringSetAsync 时是否还有其他需要处理的异常?
【问题讨论】:
标签: redis stackexchange.redis azure-redis-cache