Integrating Redis Cache In .NET Core 6

Introduction

In today's fast-paced digital world, applications are expected to deliver high performance and responsiveness. One way to achieve this is by implementing caching mechanisms that store frequently accessed data, reducing the need to fetch it from the database repeatedly. Redis, a popular in-memory data store, provides a robust caching solution for .NET Core applications. In this article, we will explore how to integrate Redis cache in a .NET Core 6 application with practical examples.

Prerequisites

Before we begin, make sure you have the following prerequisites installed on your system.

  1. .NET Core 6 SDK: Ensure you have .NET Core 6 SDK or later installed. You can download it from the official .NET website.
  2. Redis Server: Install and run a Redis server locally or use a Redis cloud service.

Install Radis Server on Window


Download Redis

You can download a moderately out-of-date precompiled version of Redis for 64-bit Windows from this GitHub page: https://github.com/MicrosoftArchive/redis/releases/download/win-3.0.504/Redis-x64-3.0.504.msi

By clicking this link, you will get a .msi file which is a Windows installer. Now go to your Downloads folder and find this file.

Now click on that file and install Redis.

Redis Server should have been installed to C:\Program Files\Redis. There you’ll find a .exe file called redis-server.

Server on Window

Now open a command line and enter this command.

redis-server

 open a command line

Your Redis server started to run.

Now you can monitor the updates and changes in the Redis server by this command.

redis-cli monitor

Redis server started to run.

Create a .NET Core 6 Console Application

dotnet new console -n RedisCacheDemo

Navigate to the project folder

cd RedisCacheDemo

Install Required Packages

dotnet add package StackExchange.Redis

Configure Redis Connection

In the Program.cs file, add the necessary statement, and configure the Redis connection in the Main method:

static void Main(string[] args)
{
    var configuration = ConfigurationOptions.Parse("localhost:6379");
    var redisConnection = ConnectionMultiplexer.Connect(configuration);
    var redisCache = redisConnection.GetDatabase();

    Console.WriteLine("Fetching data with caching:");

    var cachedData = GetDataWithCaching(redisCache);
    Console.WriteLine($"Result: {cachedData}");

    Console.WriteLine("Fetching data without caching:");
    var uncachedData = GetDataFromDatabase();

    Console.WriteLine($"Result: {uncachedData}");
    redisConnection.Close(); //It is important to close the connection
}
static string GetDataFromDatabase()
{
    // Simulate fetching data from the database
    // Replace this with your actual database fetching logic
    Thread.Sleep(2000); // Simulating latency

    return "Start";
}
static string GetDataWithCaching(IDatabase redisCache)
{
    //    redisCache.KeyDelete("cachedData"); // For Delete the Cache
   // redisCache.StringSet("cachedData", "Test", TimeSpan.FromMinutes(1)); // For Update the Cache
    string cachedData = redisCache.StringGet("cachedData");
    if (string.IsNullOrEmpty(cachedData))
    {
        cachedData = GetDataFromDatabase();
        redisCache.StringSet("cachedData", cachedData, TimeSpan.FromMinutes(1));
    }
    return cachedData;
}

Please proceed with the execution of this program.

 proceed with the execution

In this output, the result with and without cache is the same. This is because the output is stored in the cache the first time it is generated. However, if there are any changes in the code, then the result will be different.

static string GetDataFromDatabase()
{
    // Simulate fetching data from the database
    // Replace this with your actual database fetching logic
    Thread.Sleep(2000); // Simulating latency

    return "Last";
}

I updated the code's value and will rerun it.

output

In this output, the first value is retrieved from the cache, and the second value is retrieved without using the cache.

Conclusion

Congratulations! You have successfully integrated the Redis cache into your .NET Core 6 application. By implementing caching, you have improved the performance and responsiveness of your application, making it more efficient in handling frequently accessed data.


Similar Articles