如果 Redis 缓存失败则执行一个函数

Execute a function if Redis cache fails

我正在开发 .NET Core 3.1 应用程序。使用 'StackExchange.Redis' 库来处理 Redis 上的缓存操作。

在 Startup.cs

中配置连接字符串
services.AddStackExchangeRedisCache(options => {
    options.Configuration = Configuration.GetValue<string>("localhost:6379");
    options.InstanceName = "laserlamb:"; 
});

此静态 class 向 IDistributedCache 添加 'SetRecord' 功能:

    public static class DistributedCache
    {
        public static bool isCacheAvailable = true;
        static DistributedCache()
        {

        }
        
        public static async Task SetRecord(this IDistributedCache cache, string recordId, string value)
        {
            try
            {
                if (this.isCacheAvailable)
                {
                    await cache.SetStringAsync(recordId, value);
                }
            }
            catch (Exception e)
            {
                Log.Error(e.Message);
            }
        }
    }

使用依赖注入对象在缓存中设置记录。

public class SomeRandomClass
{
    private IDistributedCache cache;
    public SomeRandomClass(IDistributedCache cache) { this.cache = cache; }
    
    public async Task SaveToCache()
    {
        await cache.SetRecord("Key", "Value");
    }
}

如果我的 Redis 实例不是 运行,则会抛出错误。

当缓存不可用时,如何更新 isCacheAvailable

我想你想检查一下 Polly Project。它有 Retry/WaitAndRetry/RetryForeverCircuit Breakers 可以派上用场。

您有 Plugin 的 Microsoft DistributedCache 提供商。

检查一下。