Skip to content

Implementing Distributed Caching with Redis in ASP.NET

TLDR

  • For Windows environments, it is recommended to use WSL 2 or Docker to install Redis; using the legacy installer archived by Microsoft is not recommended.
  • For development environments, Memurai can be used as a Windows-compatible alternative to Redis.
  • When installing Redis via Docker, if external connections fail, you need to adjust the bind and protected-mode settings in redis.conf.
  • For ASP.NET Core, it is recommended to use the IDistributedCache interface to implement distributed caching; if you are in a single-server environment, IMemoryCache offers better performance.
  • For ASP.NET Framework, you can use the StackExchange.Redis package to access Redis directly via ConnectionMultiplexer.

Installing Redis on Windows

Redis does not natively support Windows. If you need to develop or test in a Windows environment, the following approaches are recommended:

  • WSL 2: The officially recommended solution, offering the best performance and stability.
  • Memurai: A Redis-compatible Windows port, suitable for development and testing environments.
  • Docker: Installed via the official image, suitable for containerized deployments.

Notes on Installing via Docker

When you might encounter issues: When running Redis inside a Docker container, but external applications cannot connect.

  • If you need custom configurations, please mount the redis.conf file.
  • If a Connection refused error occurs, please check the redis.conf settings:
    • Comment out bind 127.0.0.1 -::1 to allow external connections.
    • Change protected-mode yes to protected-mode no.

Example docker-compose.yml configuration:

text
version: '3.8'

services:
  Redis-Server:
    image: redis:7
    container_name: Redis-Server
    ports:
      - 6379:6379
    volumes:
      - .\Volumes\Data:/data
      - .\Volumes\Config:/usr/local/etc/redis
    command: redis-server /usr/local/etc/redis/redis.conf
    restart: always

Using Caching in ASP.NET Core

MemoryCache (In-Memory Caching)

When you might encounter issues: When the application is deployed on a single server and does not need to share state across machines.

  • Use the IMemoryCache interface.
  • Strategy selection:
    • Absolute: Absolute expiration time; the item is removed once the time expires.
    • Sliding: Sliding expiration time; the expiration time is extended if the item is accessed continuously.

IDistributedCache (Distributed Caching)

When you might encounter issues: When the application is deployed on multiple servers and needs to share cached data.

  • Use the Microsoft.Extensions.Caching.StackExchangeRedis package.
  • Register the service:
csharp
builder.Services.AddStackExchangeRedisCache(options => {
    options.Configuration = builder.Configuration.GetConnectionString("Redis");
    options.InstanceName = "SampleInstance";
});

WARNING

If there is only one App Server, it is recommended to prioritize IMemoryCache. This is because IMemoryCache reads from local memory, which is faster than remote Redis, and the API supports a richer set of data types, whereas IDistributedCache natively only supports string.


Using Redis in ASP.NET Framework

When you might encounter issues: When you need to integrate Redis into legacy .NET Framework projects.

  • Use the StackExchange.Redis package.
  • It is recommended to use the Singleton pattern to manage ConnectionMultiplexer to maintain connection stability.
csharp
public sealed class RedisConnection {
    private static readonly Lazy<RedisConnection> lazy = new Lazy<RedisConnection>(() => new RedisConnection());

    private RedisConnection() {
        ConnectionMultiplexer = ConnectionMultiplexer.Connect("127.0.0.1:6379");
    }

    public static RedisConnection Instance => lazy.Value;
    public ConnectionMultiplexer ConnectionMultiplexer { get; }
}

Usage example:

csharp
IDatabase db = RedisConnection.Instance.ConnectionMultiplexer.GetDatabase(0);
string cachedValue = await db.StringGetAsync("CacheKey");

Change Log

  • 2022-11-02 Initial document creation.