0

Currently i am developing an .Netcore WebAPI. I am using Azure Cache for Redis & Nuget for this Microsoft.Extensions.Caching.StackExchangeRedis.

I have below code in StartUp

services.AddDistributedRedisCache(ch => ch.Configuration = Configuration["Redis:Connection"]);

I have implimeted the extension methods for GetAsync & SetAsync with expiration time as shown below.

public static async Task<T> GetCacheValueAsync<T>(this IDistributedCache cache, string key) where T : class   
    {
            string result = await cache.GetStringAsync(key);
            if (string.IsNullOrEmpty(result))
            {
                return null;
            }
            var deserializedObj = JsonConvert.DeserializeObject<T>(result);
            return deserializedObj;
        }
        public static async Task SetCacheValueAsync<T>(this IDistributedCache cache, string key, T value) where T : class
        {
            _ = new DistributedCacheEntryOptions
            {
    
                // Remove item from cache after duration
                AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(60),
                //AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(60)
    
                // Remove item from cache if unsued for the duration
                SlidingExpiration = TimeSpan.FromSeconds(30)
            };
    
            string result = JsonConvert.SerializeObject(value);
            //string result = value.ToJsonString();
    
            await cache.SetStringAsync(key, result);
        }

Issue:- Although i am setting AbsoluteExpirationRelativeToNow & AbsoluteExpiration (any one of these) along with SlidingExpiration (which suppose to be lessthen above 2). Hardly i am giving 1 min expiration, but keys not getting expired. so every time i am calling its same stale data. what am i missing?

lokanath das
  • 736
  • 1
  • 10
  • 35
  • sliding expiration time refers to the period before a cache item is removed if unused. – lokanath das Dec 23 '20 at 13:41
  • Hold up - you aren't _using_ the `DistributedCacheEntryOptions`. So `SetStringAsync` is _permanent_ - there is no timeout on it. – mjwills Dec 23 '20 at 13:44
  • No i am using, Check this method "SetCacheValueAsync" – lokanath das Dec 23 '20 at 13:45
  • 1
    Sure, you `new` it up and then - well nothing. You throw it (`_`) away. – mjwills Dec 23 '20 at 13:45
  • 1
    I'd suggest you may want to read the docs a little - https://learn.microsoft.com/en-us/aspnet/core/performance/caching/distributed?view=aspnetcore-5.0 https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.caching.stackexchangeredis.rediscache?view=dotnet-plat-ext-3.1 You basically forgot to pass the `DistributedCacheEntryOptions` to `SetStringAsync` – mjwills Dec 23 '20 at 13:47
  • Yes, got the Fix :), thanks for the help.. – lokanath das Dec 23 '20 at 14:10

0 Answers0