连接到服务器

将您的 .NET 应用连接到 Redis 数据库

基本连接

您可以通过向 Connect() 方法传递形如 "hostname:port" 的字符串来简单地连接到服务器(例如,"localhost:6379")。但是,您也可以使用 ConfigurationOptions 参数进行连接。使用此参数可以指定用户名、密码和许多其他选项

using NRedisStack;
using NRedisStack.RedisStackCommands;
using StackExchange.Redis;

ConfigurationOptions conf = new ConfigurationOptions {
    EndPoints = { "localhost:6379" },
    User = "yourUsername",
    Password = "yourPassword"
};

ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(conf);
IDatabase db = redis.GetDatabase();

db.StringSet("foo", "bar");
Console.WriteLine(db.StringGet("foo")); // prints bar

连接到 Redis 集群

如果可用且无需特殊配置,基本连接将使用 集群 API。但是,如果您知道多个集群节点的地址和端口,则可以在连接时在 Endpoints 参数中指定所有这些信息

ConfigurationOptions options = new ConfigurationOptions
{
    //list of available nodes of the cluster along with the endpoint port.
    EndPoints = {
        { "localhost", 16379 },
        { "localhost", 16380 },
        // ...
    },            
};

ConnectionMultiplexer cluster = ConnectionMultiplexer.Connect(options);
IDatabase db = cluster.GetDatabase();

db.StringSet("foo", "bar");
Console.WriteLine(db.StringGet("foo")); // prints bar

使用 TLS 连接到您的生产环境 Redis

部署应用时,使用 TLS 并遵循 Redis 安全指南。

在将您的应用连接到启用 TLS 的 Redis 服务器之前,请确保您的证书和私钥格式正确。

要将用户证书和私钥从 PEM 格式转换为 pfx,请使用此命令

openssl pkcs12 -inkey redis_user_private.key -in redis_user.crt -export -out redis.pfx

输入密码以保护您的 pfx 文件。

使用此代码段与您的 Redis 数据库建立安全连接。

ConfigurationOptions options = new ConfigurationOptions
{
    EndPoints = { { "my-redis.cloud.redislabs.com", 6379 } },
    User = "default",  // use your Redis user. More info https://redis.ac.cn/docs/latest/operate/oss_and_stack/management/security/acl/
    Password = "secret", // use your Redis password
    Ssl = true,
    SslProtocols = System.Security.Authentication.SslProtocols.Tls12                
};

options.CertificateSelection += delegate
{
    return new X509Certificate2("redis.pfx", "secret"); // use the password you specified for pfx file
};
options.CertificateValidation += ValidateServerCertificate;

bool ValidateServerCertificate(
        object sender,
        X509Certificate? certificate,
        X509Chain? chain,
        SslPolicyErrors sslPolicyErrors)
{
    if (certificate == null) {
        return false;       
    }

    var ca = new X509Certificate2("redis_ca.pem");
    bool verdict = (certificate.Issuer == ca.Subject);
    if (verdict) {
        return true;
    }
    Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
    return false;
}

ConnectionMultiplexer muxer = ConnectionMultiplexer.Connect(options);   
            
//Creation of the connection to the DB
IDatabase conn = muxer.GetDatabase();

//send SET command
conn.StringSet("foo", "bar");

//send GET command and print the value
Console.WriteLine(conn.StringGet("foo"));   

多路复用

尽管示例代码通常使用单个连接,但实际应用代码经常同时使用多个连接。重复打开和关闭连接效率低下,因此最好仔细管理打开的连接以避免这种情况。

其他一些 Redis 客户端库使用 连接池 来高效地重用一组打开的连接。NRedisStack 采用一种不同的方法,称为 多路复用,它通过单个连接发送所有客户端命令和响应。NRedisStack 会自动为您管理多路复用。这可以在无需额外编码的情况下提供高性能。更多信息请参阅连接池和多路复用

评价此页面
返回顶部 ↑