skip to Main Content

I am trying to implement Redis caching for the first time on a simple .NET WEB API application:

WeatherForecastController.cs:

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly IDistributedCache _cache;

    public WeatherForecastController(IDistributedCache cache)
    {
        _cache = cache;
    }

    [HttpGet(Name = "GetWeatherForecast")]
    public IEnumerable<WeatherForecast> Get()
    {
        List<WeatherForecast> weatherForecasts = new();
        string cachedCategory = _cache.GetString("weatherForecast");

        if (!string.IsNullOrEmpty(cachedCategory))
        {
            weatherForecasts = JsonConvert.DeserializeObject<List<WeatherForecast>>(cachedCategory);
        }
        else
        {
            foreach (string summary in Summaries)
            {
                WeatherForecast weatherForecast = new();
                weatherForecast.Summary = summary;

                weatherForecasts.Add(weatherForecast);
            }

            DistributedCacheEntryOptions options = new();
            options.SetAbsoluteExpiration(new TimeSpan(0, 0, 30));

            _cache.SetString("weatherForecast", JsonConvert.SerializeObject(weatherForecasts), options);
        }

        return weatherForecasts;
    }
}

Program.cs:

builder.Services.AddStackExchangeRedisCache(options => 
{
    options.Configuration = builder.Configuration.GetConnectionString("RedisConnection");
    options.InstanceName = "test";
});

If I run this endpoint, go to Azure Redis Console, and get the Keys (KEYS *), I will see the Key I used:

enter image description here

enter image description here

Now if I get the value of the Key by doing GET weatherForecast, I get nil:

enter image description here

I set the expiration to 30 seconds, so whenever I run the endpoint and do KEYS *, the key will show up for the next 30 seconds. After that, it will just return (empty array). So I believe I got the Key, expiration, and connection correct. But I’m not sure if I am actually storing the value correctly since it is showing up as nil on the Console. Is this supposed to be normal? Or am I doing something wrong? Would appreciate any insight!

2

Answers


  1. You set the InstanceName, so your key has a form of InstanceName + key from the _cache.SetString() call.

    Login or Signup to reply.
  2. Your key name seems to be testweatherforecast in this case, not weatherforecast. So nil for weatherforecast seems correct.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search