Redis Cache is a high-performance, in-memory data store that can be used as a database, cache, or message broker. It is widely used in ASP.NET applications for caching, providing faster data retrieval and reducing database load.
Follow these steps to set up and use Redis Cache in your application:
// Use the NuGet Package Manager or .NET CLI to install
dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis
This package provides integration with Redis using StackExchange.Redis.
// Program.cs
var builder = WebApplication.CreateBuilder(args);
// Add Redis Cache
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = "localhost:6379"; // Replace with your Redis server address
options.InstanceName = "SampleApp_"; // Prefix for Redis keys
});
var app = builder.Build();
app.MapControllers();
app.Run();
The AddStackExchangeRedisCache
method sets up Redis as the caching provider. Replace localhost:6379
with your Redis server's address.
// Controllers/ProductController.cs
[ApiController]
[Route("api/products")]
public class ProductController : ControllerBase
{
private readonly IDistributedCache _cache;
public ProductController(IDistributedCache cache)
{
_cache = cache;
}
[HttpGet("{id}")]
public async Task GetProduct(int id)
{
string cacheKey = $"Product_{id}";
string product = await _cache.GetStringAsync(cacheKey);
if (string.IsNullOrEmpty(product))
{
// Simulate fetching data from a database
product = $"Product {id}: Sample Data";
// Store data in Redis cache
await _cache.SetStringAsync(cacheKey, product, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5)
});
}
return Ok(product);
}
}
The GetStringAsync
method checks for cached data, and SetStringAsync
stores data in Redis.
// Remove data from cache
await _cache.RemoveAsync("Product_1");
Use the RemoveAsync
method to delete data from the cache when it becomes invalid or outdated.
// First Request (No cache, fetches data)
GET /api/products/1
Response: "Product 1: Sample Data"
// Subsequent Requests (Served from cache)
GET /api/products/1
Response: "Product 1: Sample Data"
// After Cache Expiration or Removal
GET /api/products/1
Response: "Product 1: Sample Data" (Fetched and cached again)
Test the caching behavior using tools like Postman or your browser.