How to Connect to Redis via C#?

Jin Vincent Necesario
2 min readApr 3, 2023

--

Photo by Kelvin Ang on Unsplash

Connecting To Redis Server

Before we can connect to the Redis server using minimal API, we need to install the Nuget package. Microsoft.Extensions.Caching.StackExcangeRedis.

Once it is installed, connecting to the Redis server is easy. However, we need to add a section inside our appsettings.json that will help us to configure the connectivity to our Redis server.

 "RedisConnection":
{
"Host": "localhost",
"Port": "6379",
"IsSSL": false,
"Password": ""
}

Just by adding this section inside the appsetting.json. We are OK to go.

Let’s try to modify Program.cs you can copy and paste the code below.

var builder = WebApplication.CreateBuilder(args);
var config = builder.Configuration;
var services = builder.Services;

RedisConnection redisConnection = new();
config.GetSection("RedisConnection").Bind(redisConnection);

services.AddSingleton<IConnectionMultiplexer>(option =>
ConnectionMultiplexer.Connect(new ConfigurationOptions{


EndPoints = {$"{redisConnection.Host}:{redisConnection.Port}"},
AbortOnConnectFail = false,
Ssl = redisConnection.IsSSL,
Password = redisConnection.Password

}));

var app = builder.Build();

OK, from the code sample above, after we have gotten the configuration and the services from the builder. We set it up IConnectionMultiplexer by calling the redisConnection instance and assigning the proper values into the ConfigurationOptions. Of course, the last part is where we build everything viabuilder.Build().

To test the IConnectionMultiplexer we can add a GET endpoint for that.

app.MapGet("/", async (IConnectionMultiplexer redis) =>
{
var result = await redis.GetDatabase().PingAsync();
try
{
return result.CompareTo(TimeSpan.Zero) > 0 ? $"PONG: {result}" : null;
}
catch (RedisTimeoutException e)
{
throw;
}
});

Again, from the code above, we depend on IConnectionMultiplexer the inside MapGet we have called the PingAsync method. This method helps developers if the connection is alive.

For the sample output.

Summary

We have seen how we can connect to a Redis server.

That’s all for now, guys. I hope you have enjoyed this article.

You can also find the sample code here on GitHub.

Till next time, happy programming!

--

--

Jin Vincent Necesario
Jin Vincent Necesario

Written by Jin Vincent Necesario

https://www.jinoncode.dev/ - For sharing software engineering knowledge, see you there!

No responses yet