我需要在我的 asp.net 核心项目中使用 Microsoft.Extensions.Caching.Redis。
我将此代码放入 ConfigureService (Startup.cs) 中:
IDistributedCache cache = new RedisCache(new RedisCacheOptions
{
Configuration = Configuration.GetConnectionString("Redis"),
InstanceName = "Master"
});
services.AddSingleton<IDistributedCache>(cache);
我需要的是捕获连接异常(以防Redis服务器宕机,或者服务器无法访问),但是我还没有找到检查连接的方法,如果我将代码包装到try/catch中没有任何反应。
有没有办法完成我的任务?
谢谢
最佳答案
在这一步,您还没有打开与 Redis 的连接,您只创建了一个 RedisCache 的实例。类。
连接将在您使用该类的公共(public)方法时打开。以 RedisCache.GetAsync
方法为例:
// IDistributedCache _cache;
// ...
// This is the place where you may get the exception
var value = await _cache.GetAsync(key);
此处将使用私有(private) Connect 在内部(如果需要)创建连接方法。
关于c# - Catch Microsoft.Extensions.Caching.Redis 连接失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44199798/