首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在使用AddDistributedRedisCache时设置IDistributedCache.SetAsync的过期时间

在使用AddDistributedRedisCache时设置IDistributedCache.SetAsync的过期时间
EN

Stack Overflow用户
提问于 2019-02-20 04:35:40
回答 1查看 3.6K关注 0票数 4

我正在使用带有aws redis缓存的.net核心应用程序接口(2.1)。我看不出有什么方法可以将过期时间设置为IDistributedCache.SetAsync。这怎么可能呢?

我的代码片段如下:

代码语言:javascript
复制
// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddDistributedRedisCache(options =>
    {
        var redisCacheUrl = Configuration["RedisCacheUrl"];
        if (!string.IsNullOrEmpty(redisCacheUrl))
        {
            options.Configuration = redisCacheUrl;
        }
    });
}
代码语言:javascript
复制
//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;
}

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-20 04:40:02

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

代码语言:javascript
复制
await _distributedCache.SetAsync(cacheKey, Encoding.UTF8.GetBytes(encodedResult), new DistributedCacheEntryOptions
{
    AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1)
});
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54774517

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档