Redis Object Cache – WordPress plugin | WordPress.org

Introduction

When you build an ASP.NET Core application, one of the biggest challenges is performance. As your application grows and more users start using it, your database gets hit again and again for the same data. This slows down your application and increases server load.

This is where distributed caching with Redis helps.

Instead of calling the database every time, you store frequently used data in a fast in-memory system like Redis. The next time someone requests the same data, it is returned instantly from the cache instead of the database.

In this guide, you will learn step-by-step how to use Redis distributed caching in ASP.NET Core in simple and practical terms.

What is Distributed Caching?

Distributed caching means storing your cached data outside your application, usually in a separate service like Redis.

In a normal (in-memory) cache, data is stored inside a single server. If your application runs on multiple servers, each server will have its own cache, which can cause inconsistency.

But in distributed caching:

In simple words, distributed cache is like a shared memory that all your application servers can use.

What is Redis?

Redis is a very fast, in-memory data store that is widely used for caching.

Think of Redis as a super-fast dictionary where:

Why developers prefer Redis:

Prerequisites

Before starting, make sure you have the following ready:

If Redis is not installed locally, you can use Docker or any cloud provider.

Step 1: Install Required NuGet Package

First, you need to install the Redis caching package.

Run the following command:

dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis

This package connects your ASP.NET Core application with Redis and enables distributed caching support.

Step 2: Configure Redis in ASP.NET Core

Next, you need to tell your application how to connect to Redis.

Open your Program.cs file and add the following configuration:

builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = "localhost:6379";
    options.InstanceName = "SampleApp_";
});

Explanation in simple terms:

If you are using cloud Redis, replace the localhost value with your connection string.

Step 3: Inject IDistributedCache Service

ASP.NET Core provides a built-in interface called IDistributedCache to work with Redis.

You need to inject it into your service or controller.

public class ProductService
{
    private readonly IDistributedCache _cache;

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

In simple words, this allows your class to talk to Redis.

Step 4: Store Data in Redis Cache

To store data in Redis, you use the SetStringAsync method.

public async Task SetCacheDataAsync(string key, string value)
{
    var options = new DistributedCacheEntryOptions
    {
        AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)
    };

    await _cache.SetStringAsync(key, value, options);
}

What is happening here:

Why expiration is important:

Step 5: Retrieve Data from Cache

To get data from Redis, you use:

public async Task<string> GetCacheDataAsync(string key)
{
    return await _cache.GetStringAsync(key);
}

If the data exists, it returns instantly.
If not, it returns null.

This is much faster than calling the database.

Step 6: Implement Cache-Aside Pattern

The most common way to use caching is the Cache-Aside pattern.

This means:

  1. First check cache

  2. If data exists → return it

  3. If not → fetch from database and store in cache

Example:

public async Task<string> GetProductAsync(string productId)
{
    string cacheKey = $"product_{productId}";

    var cachedData = await _cache.GetStringAsync(cacheKey);

    if (!string.IsNullOrEmpty(cachedData))
    {
        return cachedData;
    }

    var productData = "Product from Database";

    await _cache.SetStringAsync(cacheKey, productData, new DistributedCacheEntryOptions
    {
        AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5)
    });

    return productData;
}

This approach:

Step 7: Working with Complex Objects

Redis stores data as strings, so for objects, you need to convert them into JSON.

public async Task SetObjectAsync<T>(string key, T data)
{
    var jsonData = JsonSerializer.Serialize(data);

    await _cache.SetStringAsync(key, jsonData);
}

public async Task<T> GetObjectAsync<T>(string key)
{
    var jsonData = await _cache.GetStringAsync(key);

    return jsonData == null ? default : JsonSerializer.Deserialize<T>(jsonData);
}

In simple words:

Step 8: Remove Data from Cache

Sometimes you need to delete outdated or incorrect cache data.

await _cache.RemoveAsync("product_1");

This is useful when:

Step 9: Best Practices for Redis Caching

To use Redis effectively, follow these simple practices:

These practices help maintain performance and avoid issues later.

Step 10: Common Use Cases

Redis caching is commonly used for:

If data is read frequently but changes less often, it is a good candidate for caching.

Advantages of Using Redis in ASP.NET Core

Using Redis gives several benefits:

It is especially useful in high-traffic applications.

Summary

Distributed caching with Redis in ASP.NET Core is a simple yet powerful way to improve application performance. Instead of repeatedly calling the database, you store frequently used data in Redis and retrieve it quickly when needed. By following the step-by-step approach, using patterns like Cache-Aside, and applying best practices, you can build fast, scalable, and efficient applications. Start small, implement caching where it matters most, and gradually optimize your system for better performance.