Sai A Sai A
Updated date May 15, 2023
In this article, we will discuss to implement distributed caching with Redis in .NET Core. We have learned about the advantages of distributed caching, Redis, and how to configure Redis in .NET Core. We have also learned how to implement the Redis cache provider and how to use the Redis cache provider in .NET Core.

Introduction:

Caching is a mechanism that helps to store data in memory and retrieve it quickly without having to hit the database every time a request is made. Distributed caching is a technique where caching is done on multiple machines in a network instead of a single machine. Distributed caching helps to increase the performance and scalability of the application by reducing the load on the database server.

Redis is an open-source, in-memory data structure store that is used as a database, cache, and message broker. Redis supports a wide range of data structures such as strings, hashes, lists, sets, and sorted sets. Redis is known for its high performance, scalability, and ease of use. In this article, we will see how to implement distributed caching with Redis in .NET Core.

Prerequisites:

Before we start implementing distributed caching with Redis in .NET Core, we need to have the following prerequisites.

  • .NET Core SDK 2.2 or later
  • Visual Studio 2017 or later
  • Redis server

Step 1: Creating a .NET Core Console Application

First, let's create a .NET Core console application in Visual Studio. Follow the below steps to create a new console application.

  • Open Visual Studio and select File > New > Project.
  • Select Console App (.NET Core) template and give a name to your project.
  • Click on the Create button.

Step 2: Adding Redis Package

To work with Redis in .NET Core, we need to install the StackExchange.Redis package. Follow the below steps to install the package.

  • Right-click on the project in the Solution Explorer and select Manage NuGet Packages.
  • Search for StackExchange.Redis package and install it.

Step 3: Creating a Redis Client

To connect to Redis server, we need to create a Redis client. We can create a Redis client by using the ConnectionMultiplexer class provided by the StackExchange.Redis package. ConnectionMultiplexer class is a thread-safe object that can be shared across multiple threads in an application. Follow the below code to create a Redis client.

var redis = ConnectionMultiplexer.Connect("localhost");
var db = redis.GetDatabase();

In the above code, we are creating a Redis client by connecting to the Redis server running on the localhost. Once we have the Redis client, we can get a reference to the database by using the GetDatabase() method.

Step 4: Caching Data in Redis

Once we have the Redis client, we can cache data in Redis by using the Set() method provided by the StackExchange.Redis package. Follow the below code to cache data in Redis.

db.StringSet("key", "value");

In the above code, we are caching a string value with a key "key" in Redis. We can also set the expiration time for the cached data by using the TimeSpan parameter. Follow the below code to cache data with an expiration time.

db.StringSet("key", "value", TimeSpan.FromMinutes(5));

In the above code, we are caching a string value with a key "key" in Redis with an expiration time of 5 minutes.

Step 5: Retrieving Data from Redis

Once we have cached the data in Redis, we can retrieve the data by using the Get() method provided by the StackExchange.Redis package. Follow the below code to retrieve data from Redis.

var value = db.StringGet("key");

In the above code, we are retrieving the value of the key "key" from Redis.

Step 6: Implementing Distributed Caching with Redis

To implement distributed caching with Redis, we need to create a Redis cache provider. Follow the below code to create a Redis cache provider.

public class Redis
CacheProvider : IDistributedCache
{
private readonly IDatabase _database;
public RedisCacheProvider()
{
    var redis = ConnectionMultiplexer.Connect("localhost");
    _database = redis.GetDatabase();
}

public byte[] Get(string key)
{
    return _database.StringGet(key);
}

public async Task<byte[]> GetAsync(string key)
{
    return await _database.StringGetAsync(key);
}

public void Refresh(string key)
{
    // Redis automatically refreshes the cache if the data is still available
}

public async Task RefreshAsync(string key)
{
    // Redis automatically refreshes the cache if the data is still available
    await Task.CompletedTask;
}

public void Remove(string key)
{
    _database.KeyDelete(key);
}

public async Task RemoveAsync(string key)
{
    await _database.KeyDeleteAsync(key);
}

public void Set(string key, byte[] value, DistributedCacheEntryOptions options)
{
    TimeSpan? expiration = null;

    if (options.AbsoluteExpirationRelativeToNow.HasValue)
    {
        expiration = options.AbsoluteExpirationRelativeToNow.Value;
    }
    else if (options.SlidingExpiration.HasValue)
    {
        expiration = options.SlidingExpiration.Value;
    }

    _database.StringSet(key, value, expiration);
}

public async Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options)
{
    TimeSpan? expiration = null;

    if (options.AbsoluteExpirationRelativeToNow.HasValue)
    {
        expiration = options.AbsoluteExpirationRelativeToNow.Value;
    }
    else if (options.SlidingExpiration.HasValue)
    {
        expiration = options.SlidingExpiration.Value;
    }

    await _database.StringSetAsync(key, value, expiration);
}
}

In the above code, we have implemented the IDistributedCache interface provided by the .NET Core framework. We have used the IDatabase interface provided by the StackExchange.Redis package to interact with Redis. We have implemented the Get(), GetAsync(), Remove(), RemoveAsync(), and Set(), SetAsync() methods to get, remove, and cache data in Redis.

Step 7: Registering Redis Cache Provider

Once we have implemented the Redis cache provider, we need to register the Redis cache provider in the .NET Core application. Follow the below code to register the Redis cache provider.

services.AddDistributedRedisCache(options =>
{
options.Configuration = "localhost";
options.InstanceName = "SampleInstance";
});

In the above code, we are registering the Redis cache provider in the .NET Core application by using the AddDistributedRedisCache() extension method. We are passing the Redis server configuration and instance name to the options parameter.

Step 8: Using Redis Cache Provider

Once we have registered the Redis cache provider, we can use the Redis cache provider in the .NET Core application. Follow the below code to use the Redis cache provider.

public class HomeController : Controller
{
private readonly IDistributedCache _cache;
public HomeController(IDistributedCache cache)
{
    _cache = cache;
}

public IActionResult Index()
{
    var data = _cache.GetString("key");

    if (string.IsNullOrEmpty(data))
    {
        // Cache miss
        data = "Hello, World!";
        var options = new DistributedCacheEntryOptions()
            .SetSlidingExpiration(TimeSpan.FromMinutes(5));
        _cache.SetString("key", data, options);
    }
    else
    {
        // Cache hit
    }

    return Content(data);
}
}

In the above code, we are injecting the IDistributedCache interface in the HomeController constructor. We are using the GetString() method to get the data from the Redis cache. If the data is unavailable in the Redis cache, we are setting the data in the Redis cache using the SetString() method.

Conclusion:

In this article, we have learned how to implement distributed caching with Redis in .NET Core. We have learned about the advantages of distributed caching, Redis, and how to configure Redis in .NET Core. We have also learned how to implement the Redis cache provider and how to use the Redis cache provider in .NET Core.

Distributed caching is an essential part of building high-performance and scalable applications. Redis is a fast, reliable, and easy-to-use distributed cache system that can help us improve the performance of our applications.

Comments (0)

There are no comments. Be the first to comment!!!