Redis Distributed Cache in C#.NET with Examples
Today in this article, we shall see how to use Redis Distributed Cache in C#.NET with Examples.
We will see how cache can play important role improving a system’s performance and scalability and best user experience.
We will cover below aspects,
I have used API with SQL server data access using the Entity framework example in this article.
Once data with key-value pair is cached, then every consecutive data access for the same will be done through the cache.
What is Caching?
- Caching is a strategy for improving a system’s performance and scalability.
- Caching lets you temporarily copy and let you access frequently used data from the storage near the application.
- Caching increases response times for client applications by supplying the data more quickly.
What is Redis Distributed Cache
Redis is a distributed in-memory database that allows you to read and write data.
Faster than Disk – Redis can respond in milliseconds or less.
They can read data faster than disk-based databases because they store data in memory.
- In Redis, all writes are asynchronous, so clients can read and write data without being interrupted.
- Redis reads the data from the snapshot or logs file and utilizes it to build the in-memory cache when it starts up.
- Redis is a key-value store that accepts simple types as well as complicated data structures like hashes, lists, and sets as values.
- It supports a set of atomic operations.
We shall cover the basic aspects of Redis cache implementation below,
- Install the Redis Nuget package.
- Configure Redis Cache in the API pipeline.
- Get the data from the cache for the input request.
Getting started
Create .NET 3.1 or 6 API or ASP.NET Core MVC applications.
Please install the Redis NuGet package Microsoft.Extensions.Caching.StackExchangeRedis
as below,
Install-Package Microsoft.Extensions.Caching.StackExchangeRedis -Version 5.0.0
Note- Please use any latest available compatible version.
Redis Distributed cache in C#.NET
Please add Redis services to the Service collection as below,
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddScoped<IEmployeeRepository, EmployeeRepository>();
services.AddSingleton<IRedisCacheService, RedisCacheService>();
services.AddDbContext<EmployeeContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("EmployeeDB"),
sqlServerOptionsAction: sqlOptions =>
{
sqlOptions.EnableRetryOnFailure();
});
});
services.AddStackExchangeRedisCache(options =>
{
options.Configuration = $"{Configuration.GetValue<string>("RedisCache:Host")}:{Configuration.GetValue<int>("RedisCache:Port")}";
});
AddStackExchangeRedisCache – It let you add Redis-distributed caching services to the specified IServiceCollection.
Let’s define a simple interface with Read and Write access,
public interface IRedisCacheService
{
T Get<T>(string key);
T Set<T>(string key, T value);
}
Redis Cache using IDistributedCache interface
Below is the basic implementation of the interface method.
Above we have registered the implementation of IDistributedCache using a wrapper interface i.e IRedisCacheService.
IRedisCacheService interface provides the below methods to work with the distributed cache.
public class RedisCacheService : IRedisCacheService
{
private readonly IDistributedCache _cache;
public RedisCacheService(IDistributedCache cache)
{
_cache = cache;
}
public T Get<T>(string key)
{
var value = _cache.GetString(key);
if (value != null)
{
return JsonSerializer.Deserialize<T>(value);
}
return default;
}
}
Below is a generic Set method that will save or write data to Redis Cache.
public T Set<T>(string key, T value)
{
var timeOut = new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(24),
SlidingExpiration = TimeSpan.FromMinutes(60)
};
_cache.SetString(key, JsonSerializer.Serialize(value), timeOut);
return value;
}
The IRedisCacheService interface is defined as below
public interface IRedisCacheService
{
T Get<T>(string key);
T Set<T>(string key, T value);
}
AbsoluteExpirationRelativeToNow and SlidingExpiration usage is explained below.
Redis cache timeout
AbsoluteExpirationRelativeToNow – That means the element added to the cache, will remain in memory for the specified time/hours, and then entry will expire from the cache whether the element is accessed or not during that time.
Example: Above AbsoluteExpirationRelativeToNow is set as 24 hours.
Item will be held in cache for the entire 24 hours and then entry will be expired.
It will be removed early only if SlidingExpiration is set, and its condition is met.
SlidingExpiration – Gets or sets how long a cache entry can be inactive (e.g. not accessed) before it will be removed.
This will not extend the entry lifetime beyond the absolute expiration (if it is set).
Example: Above SlidingExpiration is set as 60 min.
If the item is not accessed within 60 min then the item will be removed from the cache.
If it is getting accessed at least one time within 60 min then it will be held in the cache let’s say for the entire 24 hours and then entry will get expired based on AbsoluteExpiration time.
Let’s do a dependency injection of our custom Interface.
Starting RedisServer
Lets start Redis Server and start its instance to accept the data for caching.
Once we execute the API with the required input ID, first-time Employee details will be fetched from the database but next time same ID-related will be fetched directly from the cache instead of the SQL server.
Redis-Dependency Injection of the ConnectionMultiplexer
ConnectionMultiplexer StackExchange’s principal object can be leveraged using dependency injection and is recommended to use.
It provides multipurpose usage like accessing the Redis database and lets you perform read, write, update, or delete operations, provide pub/sub features, etc.
Useful References:
Do you have any comments or ideas or any better suggestions to share?
Please sound off your comments below.
Happy Coding !!
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.