Why is Azure Cache for Redis returning nil on the Console?

64 Views Asked by At

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

There are 2 best solutions below

0
Lukasz Szczygielek On

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

0
Carl Dacosta On

Your key name seems to be testweatherforecast in this case, not weatherforecast. So nil for weatherforecast seems correct.