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:
Now if I get the value of the Key by doing GET weatherForecast
, I get nil
:
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
You set the
InstanceName
, so your key has a form ofInstanceName
+key
from the_cache.SetString()
call.Your key name seems to be testweatherforecast in this case, not weatherforecast. So nil for weatherforecast seems correct.