使用AddDistributedRedisCache时设置IDistributedCache.SetAsync的到期时间 [英] Setting expiration for IDistributedCache.SetAsync while using AddDistributedRedisCache

查看:283
本文介绍了使用AddDistributedRedisCache时设置IDistributedCache.SetAsync的到期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将AWS Redis缓存与.net Core API(2.1)一起使用.我没有办法将过期设置为

I am using .net core api (2.1) with aws redis cache. I don't see a way to set expiration to the IDistributedCache.SetAsync. How is it possible?

我的代码段如下:

// 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;
}

高速缓存可用多长时间?如何设置到期时间?如果不可能,如何删除缓存?

How long the cache is available? How can I set an expiration time? If that is not possible, how can I remove the cache?

推荐答案

它位于 options 参数中.您传递 DistributedCacheEntryOptions ,它具有各种属性,可用于设置到期时间.例如:

It's in the options param. You pass an instance of DistributedCacheEntryOptions, which has various properties you can utilize to set the expire time. For example:

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

这篇关于使用AddDistributedRedisCache时设置IDistributedCache.SetAsync的到期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆