Install-Package StackExchange.Redis
Install-Package ServiceStack.Redis
instance ID:password format, and custom accounts use the username@password format. Instances with password-free authentication do not require a password.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.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:Passwordvar 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 timedb.StringSet("session:user123", "session_data", TimeSpan.FromSeconds(3600));// Hash operationsdb.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}");}}}
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 latervar manager = new PooledRedisClientManager(poolSize: 200, // Connection pool sizepoolTimeOutSeconds: 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 timeclient.Set("session:user123", "session_data", TimeSpan.FromSeconds(3600));// Hash operationsclient.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();}}
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"));}}}
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 callbackconfig.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"));}}}
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 |
Parameter | Description | Recommended Value |
poolSize | Connection pool size | 200 |
poolTimeOutSeconds | Connection acquisition timeout (s) | 3 |
readWriteHosts | Read/write node address list | - |
ConnectionMultiplexer is thread-safe and should be reused as a global singleton to avoid frequent creation and termination.フィードバック