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

问题描述

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

在 Startup.cs 中配置连接字符串

services.AddStackExchangeRedisCache(options => {
    options.Configuration = Configuration.GetValue<string>("localhost:6379");
    options.InstanceName = "laserlamb:"; 
});

这个静态类向 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。它有 Circuit BreakersDistributedCache,可以很方便。

您有 Plugin Microsoft android { // defaultConfig { ... } buildTypes { release { signingConfig signingConfigs.debug minifyEnabled false shrinkResources false } } } Provider。

检查一下。