ASIF
Redis cache

Redis Cache in asp.net Core

Redis is an open-source, in-memory data structure store used as a database, cache, and message broker. It is commonly used in ASP.NET Core applications for caching data to improve performance.

To use Redis as a cache in an ASP.NET Core application, you'll need to follow these steps:

✅ Install the Redis NuGet Package:

First, install the StackExchange.Redis NuGet package, which is a popular Redis client for .NET.

dotnet add package StackExchange.Redis

✅ Configure Redis Connection:
In your Startup.cs file, configure the Redis connection in the ConfigureServices method:

services.AddStackExchangeRedisCache(options =>
{
options.Configuration = "localhost:6379"; // Replace with your Redis server and port
options.InstanceName = "SampleInstance"; // Replace with a suitable instance name
});

✅ Using Redis Cache in a Controller:

You can now use the Redis cache in your controller by injecting IDistributedCache and using it to cache and retrieve data.

public class SampleController : Controller
{
private readonly IDistributedCache _cache;

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

public IActionResult Index()
{
// Set cache entry
string cacheKey = "sampleData";
string cachedData = _cache.GetString(cacheKey);

if (cachedData != null)
{
// Data found in cache, use it
return Ok($"Cached Data: {cachedData}");
}
else
{
// Data not found in cache, fetch from the source (e.g., database)
var data = GetDataFromSource();
cachedData = JsonConvert.SerializeObject(data);

// Set the data in the cache with a specific expiration time (e.g., 5 minutes)
var cacheEntryOptions = new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5)
};
_cache.SetString(cacheKey, cachedData, cacheEntryOptions);

return Ok($"Data from source: {cachedData}");
}
}

private List<string> GetDataFromSource()
{
// Simulate fetching data from a database or another source
return new List<string> { "Data1", "Data2", "Data3" };
}
}

In this example, we first configure the Redis cache in the Startup.cs file using AddStackExchangeRedisCache. We then use the IDistributedCache interface to cache and retrieve data in the controller. If the data is found in the cache, it is returned; otherwise, it is fetched from the source, serialized, and stored in the cache for future requests.

✅ Make sure you have a running Redis server and adjust the connection configuration accordingly in ConfigureServices. Also, customize the caching logic based on your specific requirements and data retrieval strategies.