Using Redis Locally for Caching in .NET Applications

Using Redis for Caching in .NET | Improve Performance & Scalability

Caching is an essential technique for improving the performance and scalability of applications by storing frequently accessed data in a fast-access layer. Redis, an open-source, in-memory data structure store, is one of the most popular choices for caching in modern .NET applications.

In this article, we will explore:

  • How to install and configure Redis locally
  • How to use StackExchange.Redis to cache data in a .NET application
  • How to implement distributed caching for improved performance

1. Installing and Configuring Redis Locally

1.1 Installing Redis on Windows

Redis was originally designed for Linux, but it can be run on Windows using WSL (Windows Subsystem for Linux) or a pre-built Redis binary.

Method 1: Using WSL

  1. Open PowerShell and enable WSL if not already enabled:
    wsl --install
    
  2. Install Ubuntu from the Microsoft Store.
  3. Open Ubuntu and install Redis using:
    sudo apt update
    sudo apt install redis-server
    
  4. Start Redis:
    sudo service redis-server start
    

Method 2: Using a Windows Binary

  1. Download Redis for Windows from Memurai or Microsoft’s OpenTech Redis.
  2. Extract and run redis-server.exe.
  3. Verify the installation by running:
    redis-cli ping
    
    Expected output: PONG

1.2 Installing Redis on macOS

  1. Install Homebrew if not already installed:
    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
    
  2. Install Redis:
    brew install redis
    
  3. Start Redis:
    brew services start redis
    

1.3 Installing Redis on Linux

  1. Update the package manager:
    sudo apt update
    
  2. Install Redis:
    sudo apt install redis-server
    
  3. Start the Redis service:
    sudo systemctl start redis
    
  4. Enable Redis to start on boot:
    sudo systemctl enable redis
    

2. Using StackExchange.Redis to Cache Data in .NET

2.1 Installing StackExchange.Redis

The StackExchange.Redis package is the most popular Redis client for .NET applications.

To install it, run:

Install-Package StackExchange.Redis

2.2 Connecting to Redis

Create a Redis connection in a .NET Core application:

using StackExchange.Redis;
using System;

class Program
{
    private static readonly ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
    private static readonly IDatabase cache = redis.GetDatabase();

    static void Main()
    {
        Console.WriteLine("Connected to Redis!");
    }
}

2.3 Storing and Retrieving Data

Redis supports key-value storage. Here’s how to set and get values:

cache.StringSet("username", "SandeepMhaske");
string username = cache.StringGet("username");
Console.WriteLine("Cached Username: " + username);

2.4 Implementing Object Caching

You can cache complex objects using JSON serialization:

using Newtonsoft.Json;

public class User
{
    public string Id { get; set; }
    public string Name { get; set; }
}

User user = new User { Id = "1", Name = "Sandeep Mhaske" };
string userJson = JsonConvert.SerializeObject(user);
cache.StringSet("user:1", userJson);

string retrievedJson = cache.StringGet("user:1");
User retrievedUser = JsonConvert.DeserializeObject<User>(retrievedJson);
Console.WriteLine($"Retrieved User: {retrievedUser.Name}");

2.5 Implementing Expiration Policies

You can set expiration times for cache entries:

cache.StringSet("session", "active", TimeSpan.FromMinutes(10));

3. Implementing Distributed Caching in .NET

3.1 Setting Up Distributed Caching

.NET Core provides built-in support for distributed caching with Redis. Install the required package:

Install-Package Microsoft.Extensions.Caching.StackExchangeRedis

3.2 Configuring Redis Caching in Startup.cs

Modify Program.cs (for .NET 6+):

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

var builder = WebApplication.CreateBuilder(args);

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

var app = builder.Build();
app.Run();

3.3 Using Distributed Cache in Controllers

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using System.Text.Json;
using System.Text;
using System.Threading.Tasks;

[ApiController]
[Route("api/users")]
public class UserController : ControllerBase
{
    private readonly IDistributedCache _cache;
    
    public UserController(IDistributedCache cache)
    {
        _cache = cache;
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> GetUser(int id)
    {
        string cacheKey = $"User:{id}";
        var cachedUser = await _cache.GetStringAsync(cacheKey);

        if (cachedUser != null)
        {
            return Ok(JsonSerializer.Deserialize<User>(cachedUser));
        }

        // Simulate database retrieval
        User user = new User { Id = id.ToString(), Name = "John Doe" };

        var serializedUser = JsonSerializer.Serialize(user);
        await _cache.SetStringAsync(cacheKey, serializedUser, new DistributedCacheEntryOptions
        {
            AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5)
        });

        return Ok(user);
    }
}

Conclusion

Redis is a powerful tool for improving the performance of .NET applications. By caching frequently used data, applications can reduce database load, decrease response times, and handle higher traffic efficiently.

In this guide, we covered:

  1. Installing and configuring Redis locally.
  2. Using StackExchange.Redis for basic and advanced caching.
  3. Implementing distributed caching for better scalability.

By integrating Redis effectively, your .NET applications can achieve high performance and scalability with minimal effort. 🚀

Sandip Mhaske

I’m a software developer exploring the depths of .NET, AWS, Angular, React, and digital entrepreneurship. Here, I decode complex problems, share insightful solutions, and navigate the evolving landscape of tech and finance.

Post a Comment

Previous Post Next Post