Using Redis in ASP.NET Core

Introduction

Redis is a fast, in-memory data store primarily used for caching. When we use Redis with ASP.NET Core, it improves application performance by reducing database calls and response times.

In many real-time and high-traffic applications, database queries can become slow when executed repeatedly. Redis stores frequently used data in memory, so the application can quickly fetch data without hitting the database every time.

Why Use Redis?

Redis is very fast because it stores data in memory. It helps in:

  • Caching API responses

  • Storing session data

  • Improving performance

  • Reducing database load

  • Handling high traffic smoothly

Installing Redis in ASP.NET Core

First, install the required NuGet package:

Microsoft.Extensions.Caching.StackExchangeRedis

Then configure Redis in your Program.cs file.

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

Using Redis in Controller

You can inject IDistributedCache into your controller or service.

public class HomeController : Controller
{
    private readonly IDistributedCache _cache;

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

    public async Task<IActionResult> Index()
    {
        var data = await _cache.GetStringAsync("message");

        if (data == null)
        {
            data = "Data from Database";
            await _cache.SetStringAsync("message", data);
        }

        return Content(data);
    }
}

In this example, if the data is not available in Redis, it fetches from the database and stores it in Redis. Next time, it will directly get the data from Redis, which is much faster.

Conclusion

Using Redis in ASP.NET Core is a simple and powerful way to improve performance. It is very useful in real-world applications where speed and scalability are important. By caching frequently used data, we can build faster and more efficient applications.