asp.net-core-2.1 - 使用 AddDistributedRedisCache 时为 IDistributedCache.SetAsync 设置过期时间

标签 asp.net-core-2.1 redis-cache

我正在使用带有 aws redis 缓存的 .net core api (2.1)。我没有看到将到期时间设置为 IDistributedCache.SetAsync 的方法.这怎么可能?

我的代码段如下:

// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddDistributedRedisCache(options =>
    {
        var redisCacheUrl = Configuration["RedisCacheUrl"];
        if (!string.IsNullOrEmpty(redisCacheUrl))
        {
            options.Configuration = redisCacheUrl;
        }
    });
}

//Set & GetCache
public async Task<R> GetInsights<R>(string cacheKey, IDistributedCache _distributedCache)
{
    var encodedResult = await _distributedCache.GetStringAsync(cacheKey);               

    if (!string.IsNullOrWhiteSpace(encodedResult))
    {
    var cacheValue = JsonConvert.DeserializeObject<R>(encodedResult);
    return cacheValue;
    }

    var result = GetResults<R>(); //Call to resource access
    var encodedResult = JsonConvert.SerializeObject(result);
    await _distributedCache.SetAsync(cacheKey, Encoding.UTF8.GetBytes(encodedResult)); //Duration?

    return result;
}


缓存可用多长时间?如何设置过期时间?如果这是不可能的,我该如何删除缓存?

最佳答案

它在 options参数。你传递了一个 DistributedCacheEntryOptions 的实例,它具有各种属性,您可以利用它来设置过期时间。例如:

await _distributedCache.SetAsync(cacheKey, Encoding.UTF8.GetBytes(encodedResult), new DistributedCacheEntryOptions
{
    AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1)
});

关于asp.net-core-2.1 - 使用 AddDistributedRedisCache 时为 IDistributedCache.SetAsync 设置过期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54774517/

相关文章:

c# - 在 .NET Core 2.1 中使用 AOP 进行日志记录

node.js - 如何在node js中配置redis客户端

python - Redis 可以写出到像 PostgreSQL 这样的数据库吗?

c# - 没有属性名称的Http get和post方法

.net - 使用.net core 2.1和Azure上传大文件

redis - 创建 Redis 对象并在调用方法时执行命令时出错

redis - 在 Redis 中实现具有唯一元素的队列

java - 如何从redis缓存取回Long(数据类型)值

c# - 如何在 ActionFilterAttribute 的 OnActionExecuting 中区分 C# 中的两个 rest 调用

templates - 如何在 ASP.NET Core 2.1 中向 Visual Studio 添加新的 Razor 页面模板?