Today in this article, we shall see how to use Redis Distributed cache in .NET or .NET Core C# application using Redis-Dependency Injection Of The ConnectionMultiplexer.
Today in this article, we will cover below aspects,
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.
We already covered the basic approach of using StackExchange.Redis and generic IDistributedCache interface.
Please refer to the below article for more details,
What is ConnectionMultiplexer
- ConnectionMultiplexer StackExchange’s principal object has multipurpose usage like accessing the Redis database and letting you perform read, write, update or delete operations, provide pub/sub features, etc.
- It is a thread-safe and ready-to-use application. All of the following examples will presume you have a ConnectionMultiplexer instance saved for later usage.
- The ConnectionMultiplexer is designed to be shared and reused between callers.
- Per operation, you should not establish a ConnectionMultiplexer.
- It recommends sharing and reusing the ConnectionMultiplexer object. In the below example, we are creating a singleton instance and using it for all request processing.
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 <version>
Configure Redis using Dependency Injection of the ConnectionMultiplexer Redis
Configure Redis using Dependency Injection of stackexchange.redis as below by registering IConnectionMultiplexer
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddScoped<ISalaryRepository, SalaryRepository>();
services.AddDbContext<EmployeeContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("EmployeeDB"),
sqlServerOptionsAction: sqlOptions =>
{
sqlOptions.EnableRetryOnFailure();
});
});
if (_hostEnvironment.IsDevelopment())
{
services.AddDistributedMemoryCache();//Use this for only DEV testing purpose
}
else
{
services.AddSingleton<IConnectionMultiplexer>(sp =>
ConnectionMultiplexer.Connect(new ConfigurationOptions
{
EndPoints = { $"{Configuration.GetValue<string>("RedisCache:Host")}:
{Configuration.GetValue<int>("RedisCache:Port")}" },
AbortOnConnectFail = false,
}));
}
Above you can use ConnectionMultiplexer.Connect
or ConnectionMultiplexer.ConnectAsync
, passing in either a configuration string or a ConfigurationOptions
object.
If you have SSL enabled please use the below setting to connect to the Redis cache setting,
services.AddSingleton<IConnectionMultiplexer>(sp => ConnectionMultiplexer.Connect(new ConfigurationOptions
{
EndPoints = { $"{Configuration.GetValue<string>("RedisCache:Host")}:{Configuration.GetValue<int>("RedisCache:Port")}" },
Ssl = true,
AbortOnConnectFail = false,
}));
Redis Connection for Replica set
If you have a master/replica setup then specify the connection using the below approach. Redis will identify the master automatically and establish the connection.
ConnectionMultiplexer.Connect("ServerA:6379,ServerB:6379, ServerC:6379");
Configure ConnectionMultiplexer using Dependency Injection as below,
Starting RedisServer
I have below used the WSL way to install Redis Server and started its instance to accept the data for caching.
Now once you start API and hit the endpoint first access of the requested ID will serve from the actual DB and any consecutive access will fetch directly from the cache instead of the SQL server.
Redis supports both synchronous and asynchronous implementations.
Redis – IDistributedCache interface
If you want to leverage the IDistributedCache interface, please see the below article for more details
References:
That’s all! Hope you find this article useful,
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.
Thank you for your sharing. it was very useful for me.
Thank you Kemal, Glad it helped you!
Thanks so much, I was getting multiple connections when I checked “client list” on Redis Server.
I created a singleton service in which I was injecting ConnectionMultiplexer in constructor.
Good one!
Thanks Syed for your comments. Glad that the article was helpful to you (Due to comments size limitation your sample code is trimmed but appreciate your inputs)
It is better not to call ConnectionMultiplexer.Connect in your ConfigureServices function (during startup), rather do the connect during a warmup or on demand. eg.
services.AddSingleton(sp => ConnectionMultiplexer.Connect(new ConfigurationOptions
{
EndPoints = { $”{Configuration.GetValue(“RedisCache:Host”)}:
{Configuration.GetValue(“RedisCache:Port”)}” }
}););
Hello Harman- Great point! Updated the content. Thank you for your inputs!