帮你快速理解、总结文档立即下载

.Net 连接示例

最近更新时间:2026-10-20 11:39:02
本文档已由 AI 辅助审校
我的收藏
本文介绍使用 .Net 客户端通过代理模式和直连模式连接腾讯云分布式缓存数据库实例的示例。

准备工作

环境要求

.NET Framework 4.6.1及以上版本,或 .NET Core 3.1 及以上版本。
NuGet 包管理器。

安装客户端

推荐使用 StackExchange.Redis 客户端:
Install-Package StackExchange.Redis
或使用 ServiceStack.Redis 客户端:
`dotnet add package ServiceStack.Redis`

获取连接信息

2. 在实例列表中,单击目标实例 ID,进入实例详情页。
3. 在网络信息区域,获取实例的连接地址和端口号。
代理模式:获取 VIP 地址和端口(默认6379)。
直连模式:获取各分片节点地址和端口(默认6379)。
4. 在配置信息区域,获取实例的连接密码。代理模式与直连模式的认证方式不同:
代理模式:默认账号使用 实例 ID:密码 格式,自定义账号使用 用户名@密码 格式;免密认证实例无需密码。
直连模式:复用 Redis 原生 ACL 认证机制,不支持 用户名@密码 拼接格式,支持以下两种认证方式:
默认账号:仅需密码,即 AUTH password。
自定义账号:需同时指定账号名与密码,即 AUTH account password。

代理模式连接示例

代理模式下,客户端通过 Proxy 代理层提供的统一 VIP 地址连接实例,Proxy 自动处理请求路由和故障转移,客户端无需感知后端拓扑变化。
说明:
代理模式服务端支持多 DB(默认分配256个 DB),但 StackExchange.Redis 因自身实现限制可能无法使用 SELECT 命令切换数据库,此时只能使用 DB0。如业务依赖多 DB,请改用支持 SELECT 命令的客户端。

StackExchange.Redis 连接示例(推荐)

using System;
using StackExchange.Redis;

class Program
{
static void Main(string[] args)
{
string host = "192.xx.xx.2";
int port = 6379;
string password = "crs-xxxx:密码"; // 默认账号密码格式:实例ID:密码

var config = new ConfigurationOptions
{
EndPoints = { { host, port } },
Password = password,
DefaultDatabase = 0,
ConnectTimeout = 2000, // 连接超时(毫秒)
SyncTimeout = 2000, // 同步超时(毫秒)
ConnectRetry = 3, // 连接重试次数
KeepAlive = 30, // 心跳间隔(秒)
AbortOnConnectFail = false // 连接失败不终止
};

using (var redis = ConnectionMultiplexer.Connect(config))
{
var db = redis.GetDatabase();

// 写入数据
db.StringSet("name", "腾讯云分布式缓存数据库");

// 读取数据
var value = db.StringGet("name");
Console.WriteLine($"get name: {value}");

// 设置带过期时间的 Key
db.StringSet("session:user123", "session_data", TimeSpan.FromSeconds(3600));

// 哈希操作
db.HashSet("user:1001", new HashEntry[]
{
new HashEntry("name", "张三"),
new HashEntry("age", "28")
});
var userName = db.HashGet("user:1001", "name");
Console.WriteLine($"user name: {userName}");

// 列表操作
db.ListLeftPush("queue:tasks", new RedisValue[] { "task1", "task2", "task3" });
var task = db.ListRightPop("queue:tasks");
Console.WriteLine($"dequeued task: {task}");
}
}
}

ServiceStack.Redis 连接池示例

using System;
using ServiceStack.Redis;

class Program
{
static void Main(string[] args)
{
string host = "192.xx.xx.2";
int port = 6379;
string password = "crs-xxxx:密码";

// ServiceStack 4.0 及以上版本连接池
var manager = new PooledRedisClientManager(
poolSize: 200, // 连接池大小
poolTimeOutSeconds: 3, // 获取连接超时(秒)
readWriteHosts: new[] { $"{password}@{host}:{port}" }
);

using (var client = manager.GetClient())
{
// 写入数据
client.Set("name", "腾讯云分布式缓存数据库");

// 读取数据
var value = client.Get<string>("name");
Console.WriteLine($"get name: {value}");

// 设置带过期时间的 Key
client.Set("session:user123", "session_data", TimeSpan.FromSeconds(3600));

// 哈希操作
client.SetEntryInHash("user:1001", "name", "张三");
client.SetEntryInHash("user:1001", "age", "28");
var userName = client.GetValueFromHash("user:1001", "name");
Console.WriteLine($"user name: {userName}");
}

manager.Dispose();
}
}

自定义账号连接示例

using System;
using StackExchange.Redis;

class Program
{
static void Main(string[] args)
{
var config = new ConfigurationOptions
{
EndPoints = { { "192.xx.xx.2", 6379 } },
Password = "myuser@MyPassword", // 代理模式自定义账号:用户名@密码整体作为密码传入,不单独设置 User(区别于直连模式 ACL 的账号名/密码分离传参)
ConnectTimeout = 2000,
SyncTimeout = 2000,
AbortOnConnectFail = false
};

using (var redis = ConnectionMultiplexer.Connect(config))
{
var db = redis.GetDatabase();
db.StringSet("key", "value");
Console.WriteLine(db.StringGet("key"));
}
}
}

SSL 加密连接示例

using System;
using System.Security.Cryptography.X509Certificates;
using StackExchange.Redis;

class Program
{
static void Main(string[] args)
{
var config = new ConfigurationOptions
{
EndPoints = { { "192.xx.xx.2", 6379 } },
Password = "crs-xxxx:密码",
Ssl = true, // 启用 SSL
SslProtocols = System.Security.Authentication.SslProtocols.Tls12,
ConnectTimeout = 2000,
SyncTimeout = 2000,
AbortOnConnectFail = false
};

// 证书验证回调
config.CertificateValidation += (sender, cert, chain, errors) =>
{
// 加载 CA 证书进行验证
var caCert = new X509Certificate2("/path/to/ca.pfx");
return cert.Issuer == caCert.Subject;
};

using (var redis = ConnectionMultiplexer.Connect(config))
{
var db = redis.GetDatabase();
db.StringSet("ssl_test", "encrypted_connection");
Console.WriteLine(db.StringGet("ssl_test"));
}
}
}

直连模式连接示例

直连模式下,客户端使用 Redis Cluster 协议直接连接各分片节点,本地处理 MOVED/ASK 重定向,可直接使用社区标准的 Redis Cluster 客户端接入。
说明:
直连模式仅适用于集群架构实例。
需使用支持 Redis Cluster 协议的客户端(StackExchange.Redis 原生支持 Cluster 模式)。
需在控制台开启直连模式并获取各分片节点的连接地址。
认证方式复用 Redis 原生 ACL 机制:默认账号仅传密码,自定义账号需分别传入账号名与密码,不支持 用户名@密码 拼接格式。
直连模式暂不支持 SSL 加密连接。

StackExchange.Redis Cluster 连接示例

using System;
using StackExchange.Redis;

class Program
{
static void Main(string[] args)
{
// 直连模式下各分片节点地址
var config = new ConfigurationOptions
{
EndPoints =
{
{ "192.xx.xx.2", 6379 },
{ "192.xx.xx.3", 6379 },
{ "192.xx.xx.4", 6379 }
},
Password = "password", // 直连模式默认账号仅传密码,不带实例 ID 前缀
ConnectTimeout = 2000,
SyncTimeout = 2000,
ConnectRetry = 3,
KeepAlive = 30,
AbortOnConnectFail = false
};

using (var redis = ConnectionMultiplexer.Connect(config))
{
var db = redis.GetDatabase();

// 写入数据(客户端自动路由到正确的分片)
db.StringSet("cluster:key1", "value1");
db.StringSet("cluster:key2", "value2");
db.StringSet("cluster:key3", "value3");

// 读取数据
Console.WriteLine($"key1: {db.StringGet("cluster:key1")}");
Console.WriteLine($"key2: {db.StringGet("cluster:key2")}");
Console.WriteLine($"key3: {db.StringGet("cluster:key3")}");

// 哈希操作
db.HashSet("user:{1001}", new HashEntry[]
{
new HashEntry("name", "张三"),
new HashEntry("age", "28")
});
Console.WriteLine($"user name: {db.HashGet("user:{1001}", "name")}");

// 使用 Hash Tag 确保相关 Key 路由到同一分片
db.StringSet("{order:1001}:status", "paid");
db.StringSet("{order:1001}:amount", "99.00");
db.StringSet("{order:1001}:time", "2025-01-01 10:00:00");
Console.WriteLine($"order status: {db.StringGet("{order:1001}:status")}");

// 批量操作(同一 Hash Tag 的 Key)
var batch = db.CreateBatch();
batch.StringSetAsync("{batch}:k1", "v1");
batch.StringSetAsync("{batch}:k2", "v2");
batch.StringSetAsync("{batch}:k3", "v3");
batch.Execute();

Console.WriteLine($"batch k1: {db.StringGet("{batch}:k1")}");
Console.WriteLine($"batch k2: {db.StringGet("{batch}:k2")}");
}
}
}

ServiceStack.Redis 直连模式说明

说明:
ServiceStack.Redis 不支持 Redis Cluster 协议,PooledRedisClientManager 无法处理 MOVED/ASK 重定向与槽位路由,因此不适用于直连模式。如需在直连模式下连接集群实例,请使用 StackExchange.Redis(参见上文示例);ServiceStack.Redis 仅建议用于代理模式。

自定义账号(ACL)连接示例

直连模式复用 Redis 原生 ACL 认证机制,使用自定义账号时需分别传入账号名与密码,不支持 用户名@密码 拼接格式。
using System;
using StackExchange.Redis;

class Program
{
static void Main(string[] args)
{
// ===== ACL 认证机制:账号名与密码是两个独立字段 =====
// 直连模式的多账号能力基于 Redis 原生 ACL:控制台创建的每个自定义账号
// 都是一个独立的 ACL user,认证时客户端向节点发送 AUTH <account> <password>。
// 因此需将 User 与 Password 分别传入(等价于执行 AUTH account password),
// 不要写成代理模式的 "myuser@MyPassword" 拼接格式。
var config = new ConfigurationOptions
{
EndPoints =
{
{ "192.xx.xx.2", 6379 },
{ "192.xx.xx.3", 6379 },
{ "192.xx.xx.4", 6379 }
},
User = "myuser", // ACL 账号名 → AUTH account
Password = "MyPassword", // 账号密码 → AUTH password(纯密码,无需拼接)
ConnectTimeout = 2000,
SyncTimeout = 2000,
AbortOnConnectFail = false
};

using (var redis = ConnectionMultiplexer.Connect(config))
{
var db = redis.GetDatabase();
db.StringSet("key", "value");
Console.WriteLine(db.StringGet("key"));
}
}
}

连接参数说明

StackExchange.Redis 参数

参数
说明
推荐值
EndPoints
实例连接地址。代理模式为 VIP 地址,直连模式为分片节点地址
-
Password
认证密码
默认账号格式:实例 ID:密码
ConnectTimeout
连接超时(毫秒)
2000
SyncTimeout
同步操作超时(毫秒)
2000
ConnectRetry
连接重试次数
3
KeepAlive
心跳间隔(秒)
30
AbortOnConnectFail
连接失败是否终止
false

ServiceStack.Redis 参数

参数
说明
推荐值
poolSize
连接池大小
200
poolTimeOutSeconds
获取连接超时(秒)
3
readWriteHosts
读写节点地址列表
-

常见问题

连接超时

确认客户端所在 CVM 与分布式缓存数据库实例在同一 VPC 内。
确认安全组规则已放通对应端口。
确认连接地址和端口正确。

认证失败

代理模式:默认账号使用 实例 ID:密码,自定义账号使用 用户名@密码。
直连模式:复用 Redis ACL 认证,默认账号仅传密码(AUTH password),自定义账号需分别传入账号名与密码(AUTH account password),不支持 用户名@密码 拼接格式。
确认密码中无特殊字符导致解析异常。

直连模式 MOVED 错误

StackExchange.Redis 原生支持 Cluster 模式,配置多个 EndPoints 即可自动处理 MOVED 重定向。
确认已在控制台开启直连模式。
确认 EndPoints 地址为分片节点地址而非 VIP 地址。

ConnectionMultiplexer 使用建议

ConnectionMultiplexer 是线程安全的,应作为单例全局复用,避免频繁创建和销毁。
建议在应用启动时创建一次,应用退出时释放。