Tuesday, 28 May 2024

Distributed caching using Redis in asp.net core.

 To use Redis for distributed caching in ASP.Net core you need to follow below steps:

  1. Need to add NuGet package "Microsoft.Extensions.Caching.StackExchangeRedis"
  2. Need to configure Redis service via 
            builder.Services.AddStackExchangeRedisCache(option =>{
                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

How to create and use middleware in asp.net core

Middleware is piece of code that's assembled into an app pipeline to handle requests and responses.  Each middleware component in the re...