

Parse Redis-CLI Connection URI To Use With StackExchange.Redis
source link: https://khalidabuhakmeh.com/redis-cli-connection-uri-with-stackexchangeredis
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Parse Redis-CLI Connection URI To Use With StackExchange.Redis

Redis has steadily established itself as a great choice of infrastructure in modern solutions. Redis is a data structures server, which provides an interface of commands used to interact with mutable data. Developers use Redis as a key/value store for quick lookups with known keys, commonly in caching. A developer operating with .NET will most likely be using the StackExchange.Redis package to access their server instance. While connection strings for Redis can vary, many online hosting platforms provide a redis-cli connection string.
This post will see how we can write an extension method that parses a redis-cli connection string we can use with the StackExchange.Redis library.
What Is Redis-CLI
redis-cli
is a command-line interface (CLI) program that allows us to send commands to a Redis instance. The program can operate in two modes: Read Eval Print Loop (REPL) and single-command. The REPL mode assumes a developer is actively typing commands, reading the response, and repeating as needed. Developers can use the single-command method to issue one-off commands, and the program will print results to the standard output.
We can use the -u
argument when invoking redis-cli
to connect to a remote server.
redis-cli -u redis://username:password@host:port
From the CLI, we can issue commands like PING
and receive a response.
redis-cli -u redis://username:password@host:port ping
PONG
So, how do we take our redis://
URI and use that in our .NET 5+ applications?
Parsing the Redis-CLI URI
Before continuing, this post assumes you are using the StackExchange.Redis
NuGet package. To install the dependency, use the following command on the target .NET project.
dotnet add package StackExchange.Redis
As we saw in the previous section, the redis-cli
URI has a particular pattern.
redis://username:password@host:port
Let’s convert that into a Regex
pattern. We’ll also use named groups to pull the necessary values out later in the post.
^redis://(?<username>.+):(?<password>.+)@(?<host>.+):(?<port>\d+)$
Now, let’s look at how we might configure our Redis infrastructure in an ASP.NET Core application. **Note, I’ve configured the Redis dependencies in Program.cs
, but the code would be identical if placed in Startup.cs
.
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using StackExchange.Redis;
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices(collection =>
{
collection.AddSingleton(services =>
{
var config = services.GetRequiredService<IConfiguration>();
var connectionString = config["Redis"];
return ConnectionMultiplexer.Connect(
new ConfigurationOptions()
// our extension method
.FromCli(connectionString));
});
collection.AddScoped(services =>
{
var connection =
services.GetRequiredService<ConnectionMultiplexer>();
return connection.GetDatabase();
});
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
We have a FromCli
extension method, which parses the format described above. How do we implement the approach? Regular Expressions of course!
using System;
using System.Text.RegularExpressions;
using StackExchange.Redis;
public static class Redis
{
private static readonly Regex CliPattern =
new("^redis://(?<username>.+):(?<password>.+)@(?<host>.+):(?<port>\\d+)$");
public static ConfigurationOptions FromCli(string connectionString)
{
var options = new ConfigurationOptions();
FromCli(options, connectionString);
return options;
}
public static ConfigurationOptions FromCli(
this ConfigurationOptions options,
string connectionString
)
{
var match = CliPattern.Match(connectionString);
if (!match.Success)
{
throw new ArgumentException(
"Cli connection string was not correct. " +
$"Be sure it follows {CliPattern} pattern.",
nameof(connectionString));
}
var values = match.Groups;
options.EndPoints.Add($"{values["host"].Value}:{values["port"].Value}");
options.Password = values["password"].Value;
options.User = values["username"].Value;
return options;
}
}
There you have it! Now you can use your redis-cli
connection string with StackExchange.Redis
. Hopefully, you find this extension method helpful when switching between the two different ways of accessing Redis.

About Khalid Abuhakmeh
Khalid is a developer advocate at JetBrains focusing on .NET technologies and tooling.
Recommend
-
75
前言 本人从事 .netcore 转型已两年有余,对 .net core 颇有好感,这一切得益于优秀的语法、框架设计。 2006年开始使用 .net 2.0,从 asp.net 到 winform 到 winservice 等等领域开发都些许涉猎。对.net和大...
-
57
编者:.net core redis 驱动推荐,为什么不使用 StackExchange.Redis 引起了很大的反响,大家反应过度,其实StackExchange.Redis 2.0已经从重构了异步队列,使用管道方式解决...
-
34
README.md org-yt Youtube links in org-mode, see https://...
-
24
In October the Register reported that 20 Stack Exchange moderators had distanced themselves from the ge...
-
12
Die URI.parse Die; Long Live the Zen of Addressable May 12, 2020 URI.parse is a Ruby call I've written a thousand pl...
-
2
通俗易懂解释什么是PCIA(主成分分析) - stackexchange 假设我们的桌子上放着一些酒瓶。我们可以通过颜色、酒度、酒龄等来描述每种酒,而对于酒窖中每种葡萄...
-
12
BlackBox Safely store secrets in a VCS repo (i.e. Git, Mercurial, Subversion or Perforce). These commands make it easy for you to Gnu Privacy Guard (GPG) encrypt specific files in a repo so they are "encrypted at rest" in your repo...
-
4
Not FoundYou just hit a route that doesn't exist... the sadness.LoginRadius empowers businesses to deliver a delightful customer experience and win customer trust. Using the LoginRadius Identity...
-
5
关闭StackExchange等平台的privacy收集窗口 - DECHIN - 博客园 当我们打开一个StackExchange页面的时候,经常会出现一个很大的
-
7
关于stackexchange.redis的timeout异常 ...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK