Redis Cache Integration in ASP.NET

What is Redis Cache?

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.

  • Fast: Data is stored in memory, resulting in quick access.
  • Scalable: Redis can handle large-scale distributed systems.
  • Flexible: Supports various data structures like strings, lists, and hashes.

How to Integrate Redis Cache in ASP.NET

Follow these steps to set up and use Redis Cache in your application:

1. Install the Redis Package


// 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.

2. Configure Redis in Program.cs


// 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.

3. Inject IDistributedCache


// 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.

4. Remove Data from Cache


// 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.

5. Example Request and Response


// 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.