tencent cloud

Tencent Cloud Distributed Cache (Redis OSS-Compatible)

.Net Connection Sample

다운로드
포커스 모드
폰트 크기
마지막 업데이트 시간: 2026-09-07 14:31:33
AI 번역 및 품질 검수 완료
This document provides an example of using a .Net client to connect to a Tencent Cloud Distributed Cache instance.

Preparations

Environment Requirement

.NET Framework 4.6.1 or later, or .NET Core 3.1 or later.
NuGet package manager.

Installing a client

We recommend using the StackExchange.Redis client:
Install-Package StackExchange.Redis
Or use the ServiceStack.Redis client:
Install-Package ServiceStack.Redis

Obtaining Connection Information

1. Log in to the Distributed Cache console.
2. In the instance list, click the target instance ID to go to the instance details page.
3. In the Network Information section, obtain the instance's VIP address and port (default: 6379).
4. In the Configuration Information section, obtain the connection password of the instance.
Default accounts use the instance ID:password format, and custom accounts use the username@password format. Instances with password-free authentication do not require a password.

Connection Example

In proxy mode, clients connect to instances through the unified VIP address provided by the Proxy layer. The Proxy automatically handles request routing and failover, so clients do not need to be aware of backend topology changes.
Note:
Multi-DB Usage Notes: In proxy mode, the server supports multiple DBs (256 DBs are allocated by default). However, due to implementation limitations, StackExchange.Redis may not be able to use the SELECT command to switch databases, in which case only DB0 can be used. If your business depends on multiple DBs, switch to a client that supports the SELECT command.

StackExchange.Redis Connection Example (Recommended)

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:password"; // Default account password format: Instance ID:Password

var config = new ConfigurationOptions
{
EndPoints = { { host, port } },
Password = password,
DefaultDatabase = 0,
ConnectTimeout = 2000, // Connection timeout (in milliseconds)
SyncTimeout = 2000, // Synchronization timeout (in milliseconds)
ConnectRetry = 3, // Number of connection retries.
KeepAlive = 30, // Heartbeat interval (in seconds)
AbortOnConnectFail = false // Do not terminate the connection when a connection failure occurs.
};

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

// Write data.
db.StringSet("name", "Distributed Cache");

// Read data.
var value = db.StringGet("name");
Console.WriteLine($"get name: {value}");

// Set a Key with an expiration time
db.StringSet("session:user123", "session_data", TimeSpan.FromSeconds(3600));

// Hash operations
db.HashSet("user:1001", new HashEntry[]
{
new HashEntry("name", "Zhang San"),
new HashEntry("age", "28")
});
var userName = db.HashGet("user:1001", "name");
Console.WriteLine($"user name: {userName}");

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

ServiceStack.Redis Connection Pool Example

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:password";

// Connection pool for ServiceStack 4.0 and later
var manager = new PooledRedisClientManager(
poolSize: 200, // Connection pool size
poolTimeOutSeconds: 3, // Timeout for obtaining a connection (in seconds)
readWriteHosts: new[] { $"{password}@{host}:{port}" }
);

using (var client = manager.GetClient())
{
// Write data.
client.Set("name", "Distributed Cache");

// Read data.
var value = client.Get<string>("name");
Console.WriteLine($"get name: {value}");

// Set a Key with an expiration time
client.Set("session:user123", "session_data", TimeSpan.FromSeconds(3600));

// Hash operations
client.SetEntryInHash("user:1001", "name", "Zhang San");
client.SetEntryInHash("user:1001", "age", "28");
var userName = client.GetValueFromHash("user:1001", "name");
Console.WriteLine($"user name: {userName}");
}

manager.Dispose();
}
}

Custom Account Connection Example

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", // Proxy mode custom account: pass the entire "username@password" string as the password. Do not set User separately, unlike direct connection mode ACL, which separates the account name/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"));
}
}
}

SSL Encryption Connection Example

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:password",
Ssl = true, // Enable SSL.
SslProtocols = System.Security.Authentication.SslProtocols.Tls12,
ConnectTimeout = 2000,
SyncTimeout = 2000,
AbortOnConnectFail = false
};

// Certificate verification callback
config.CertificateValidation += (sender, cert, chain, errors) =>
{
// Load the CA certificate for verification.
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"));
}
}
}

Connection Parameter Description

StackExchange.Redis Parameters

Parameter
Description
Recommended Value
EndPoints
Instance connection address. In proxy mode, it is a VIP address; in direct connection mode, it is a shard node address.
-
Password
Authentication password
Default account format: instance ID:password
ConnectTimeout
Connection timeout (milliseconds)
2000
SyncTimeout
Sync operation timeout (milliseconds)
2000
ConnectRetry
Connection retry attempts
3
KeepAlive
Heartbeat interval (s)
30
AbortOnConnectFail
Whether to terminate on connection failure
false

ServiceStack.Redis Parameters

Parameter
Description
Recommended Value
poolSize
Connection pool size
200
poolTimeOutSeconds
Connection acquisition timeout (s)
3
readWriteHosts
Read/write node address list
-

FAQs

Connection Timeout

Confirm that the CVM hosting the client and the Distributed Cache instance are in the same VPC.
Confirm that the security group rule allows access to the corresponding port.
Confirm that the connection address and port are correct.

ConnectionMultiplexer Usage Recommendations

ConnectionMultiplexer is thread-safe and should be reused as a global singleton to avoid frequent creation and termination.
Create it once when the application starts, and release it when the application exits.

도움말 및 지원

문제 해결에 도움이 되었나요?

피드백