Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting expiration for IDistributedCache.SetAsync while using AddDistributedRedisCache

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?

like image 617
user007 Avatar asked Mar 04 '23 11:03

user007


1 Answers

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)
});
like image 56
Chris Pratt Avatar answered May 13 '23 12:05

Chris Pratt