gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:06:19 27 4
gpt4 key购买 nike

我正在使用带有 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com