To use Redis for distributed caching in ASP.Net core you need to follow below steps:
- Need to add NuGet package "Microsoft.Extensions.Caching.StackExchangeRedis"
- Need to configure Redis service via
string connection = builder.Configuration.GetConnectionString("redis")!;
option.Configuration = connection; //< == provide connection string;
});
3.configure redis connection in AppSettings.json
"ConnectionStrings": {
"redis": "localhost:6379"
}
4.You need to inject IDistributedCache dependency in Constructor or endpoint.
IDistributedCache provides GetString("StringKey") and SetString("StringKey","StringValue") API, to set your object in Cache you need to serialize it.
app.MapGet("/weatherforecast", (HttpContext httpContext, IDistributedCache cache) =>
{
var strCachedForcast = cache.GetString("Forecast");
if (string.IsNullOrEmpty(strCachedForcast))
{
var cachedForecaste = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = summaries[Random.Shared.Next(summaries.Length)]
}) .ToArray();
strCachedForcast = JsonSerializer.Serialize< WeatherForecast[]>(cachedForecaste );
cache.SetString("Forecast", strCachedForcast);
}
return JsonSerializer.Deserialize<WeatherForecast[]>(strCachedForcast);
})
.WithName("GetWeatherForecast")
.WithOpenApi();
No comments:
Post a Comment