Setting expiration for IDistributedCache.SetAsync while using AddDistributedRedisCache

放肆的年华 提交于 2021-01-27 12:00:53

问题


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?

My code segment is below:

// 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?


回答1:


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


来源:https://stackoverflow.com/questions/54774517/setting-expiration-for-idistributedcache-setasync-while-using-adddistributedredi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!