### Session Store Example Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/INDEX.md Provides an example of using FullRedis as a session store. It demonstrates setting and getting session data, which is stored as a dictionary with a configurable expiration time. A prefix is applied to session keys. ```csharp public class RedisSessionStore { private readonly FullRedis _redis; public RedisSessionStore() { _redis = new FullRedis("127.0.0.1:6379", null, 1) { Prefix = "session:" }; } public void SetSession(string sessionId, Dictionary data, int expire) { var hash = _redis.GetDictionary(sessionId); foreach (var kv in data) { hash[kv.Key] = kv.Value; } _redis.SetExpire(sessionId, TimeSpan.FromSeconds(expire)); } public Dictionary? GetSession(string sessionId) { var hash = _redis.GetDictionary(sessionId); return hash.Count > 0 ? hash.ToDictionary(x => x.Key, x => x.Value) : null; } } ``` -------------------------------- ### Redis Configuration in appsettings.json Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/dependency-injection.md Example of how to configure Redis connection options, including server, password, and database, within the appsettings.json file. ```json { "Redis": { "Server": "localhost:6379", "Password": "mypass", "Db": 0, "Timeout": 5000, "Prefix": "app:", "ProtocolVersion": 0 } } ``` -------------------------------- ### Target API Controller Example (C#) Source: https://github.com/newlifex/newlife.redis/blob/master/Doc/RedisSwitch项目说明.md A basic C# example of a target API controller that receives and logs messages. ```csharp [ApiController] [Route("api/[controller]")] public class TargetController : ControllerBase { private readonly ILogger _logger; public TargetController(ILogger logger) { _logger = logger; } [HttpPost] public IActionResult ReceiveMessage([FromBody] MessageData message) { _logger.LogInformation("Received message: {MessageId}, Content: {Content}", message.Id, message.Content); // 处理消息 // ... return Ok(); } } ``` -------------------------------- ### Basic Redis Client Setup and Usage Source: https://github.com/newlifex/newlife.redis/blob/master/Readme.MD Demonstrates setting up a FullRedis client with connection details and logging, then writing and reading a JSON-serialized object. Recommended for single instance, thread-safe reuse. ```csharp using NewLife.Caching; using NewLife.Log; XTrace.UseConsole(); var rds = new FullRedis("127.0.0.1:6379", "password", 0) { Log = XTrace.Log, // 可选:组件日志 AutoPipeline = 100, // 可选:命令数达到 100 自动提交管道 }; // 写入对象(自动 JSON 序列化) ds.Set("user:1", new { Name = "Alice", Age = 30 }, expire: 3600); // 读取(自动反序列化) var name = rds.Get("user:1"); Console.WriteLine(name); ``` -------------------------------- ### Redis Stream Producer and Consumer Setup Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/api-reference.md Shows how to set up a consumer group for a Redis Stream, produce messages, and consume them asynchronously with a timeout. ```csharp var redis = new FullRedis("127.0.0.1:6379"); var stream = redis.GetStream("messages"); // Setup consumer group stream.SetGroup("group1"); // Produce var msgId = stream.Add("message content"); // Consume var msg = stream.TakeOne(timeout: 0); // Block forever await stream.TakeOneAsync(timeout: 30); // Acknowledge stream.Acknowledge(msgId); // Get info var groups = stream.GetGroups(); var consumers = stream.GetConsumers("group1"); ``` -------------------------------- ### Install NewLife.Redis Package Source: https://github.com/newlifex/newlife.redis/blob/master/Readme.MD Use the dotnet CLI to add the NewLife.Redis package to your project. The `--prerelease` flag can be used for development versions. ```bash # 稳定版 dotnet add package NewLife.Redis # ASP.NET Core 扩展 dotnet add package NewLife.Redis.Extensions # 开发版(含预发布) dotnet add package NewLife.Redis --prerelease ``` -------------------------------- ### Get Command Data Flow Source: https://github.com/newlifex/newlife.redis/blob/master/Doc/架构文档.md Details the internal steps involved when executing a 'Get' command. It covers borrowing a client from the pool, constructing the RESP request, sending it over TCP, decoding the response, and returning the client to the pool. ```text 用户代码: rds.Get("user:1") │ ├─ Redis.Execute("user:1", (client, key) => client.Execute("GET", key), write=false) │ ├─ StopPipeline(check=true) // 确保无挂起管道 │ ├─ Pool.Get() → 借出 RedisClient │ ├─ RedisClient.Execute("GET", "user:1") │ ├─ 构建 RESP:*2\r\n$3\r\nGET\r\n$6\r\nuser:1\r\n │ ├─ 发送到 TCP Stream │ └─ 读取响应 $N\r\n{json}\r\n → IPacket │ ├─ Encoder.Decode(packet, typeof(User)) │ └─ JsonHost.Deserialize(json) │ └─ Pool.Return(client) // 归还连接 ``` -------------------------------- ### Handle RedisException Example Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/types.md Demonstrates how to catch and handle RedisException. This is useful for gracefully managing connection or command execution failures. ```csharp try { redis.Set("key", "value"); } catch (RedisException ex) { Console.WriteLine($"Redis error: {ex.Message}"); } ``` -------------------------------- ### HyperLogLog Example Usage Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/api-reference.md Demonstrates adding items to a HyperLogLog, retrieving its approximate count, and merging it with another HyperLogLog. ```csharp var redis = new FullRedis("127.0.0.1:6379"); var hll = redis.GetHyperLogLog("unique_users"); // Add users hll.Add("user1", "user2", "user3"); // Get approximate count var count = hll.Count; // ~3 // Merge hll.Merge("other_hll_key"); ``` -------------------------------- ### Publish Message Example using cURL Source: https://github.com/newlifex/newlife.redis/blob/master/Samples/RedisSwitch/README.md Example of publishing a message to the Redis Switch API using cURL. Includes message content and properties. ```bash curl -X POST "http://localhost:5000/api/message/publish" \ -H "Content-Type: application/json" \ -d '{ "content": "测试消息", "properties": { "source": "system", "priority": "high" } }' ``` -------------------------------- ### Query Queue Status Example using cURL Source: https://github.com/newlifex/newlife.redis/blob/master/Samples/RedisSwitch/README.md Example of querying the queue status using cURL. This helps monitor the current number of messages in the queue. ```bash curl -X GET "http://localhost:5000/api/message/status" ``` -------------------------------- ### Local Development Connection String Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/configuration.md Example of a connection string for local Redis development, specifying server, password, and database. ```csharp // Local development "server=127.0.0.1:6379;password=123456;db=0" ``` -------------------------------- ### Custom Encoder Implementation Example Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/types.md Provides an example of implementing a custom encoder by inheriting from IPacketEncoder. This allows for custom serialization logic, such as using a different JSON serializer or a binary format. ```csharp public class MyEncoder : IPacketEncoder { public Packet Encode(T obj) { // Custom encoding } public T? Decode(Packet pk) { // Custom decoding } public Object? Decode(Packet pk, Type type) { // Custom decoding } } redis.Encoder = new MyEncoder(); ``` -------------------------------- ### Basic Redis Operations Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/api-reference.md Demonstrates setting, getting, and removing a key-value pair. Ensure the Redis client is initialized with the correct connection string and authentication details. ```csharp var redis = new Redis("127.0.0.1:6379", "password", 0); // Basic operations redis.Set("key1", "value1", 3600); var value = redis.Get("key1"); redis.Remove("key1"); ``` -------------------------------- ### Message Queue Example Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/INDEX.md Illustrates the usage of FullRedis for implementing a message queue. Shows how to enqueue messages and dequeue them with an optional timeout. Assumes a generic type T for messages. ```csharp public class MessageQueue { private readonly FullRedis _redis; public MessageQueue() { _redis = new FullRedis("127.0.0.1:6379", null, 0); } public void Enqueue(string topic, T message) { var queue = _redis.GetQueue(topic); queue.Add(message); } public T? Dequeue(string topic, int timeout = -1) { var queue = _redis.GetQueue(topic); return queue.TakeOne(timeout); } } ``` -------------------------------- ### Publish Message API Request Example Source: https://github.com/newlifex/newlife.redis/blob/master/Doc/RedisSwitch项目说明.md Example JSON payload for publishing a message, including content and custom properties. ```json { "content": "这是一条测试消息", "properties": { "source": "TestSystem", "priority": "high", "timestamp": "2026-02-15T12:00:00" } } ``` -------------------------------- ### Cache Layer Example Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/INDEX.md Demonstrates how to implement a caching layer using FullRedis. It fetches data from the cache or fetches it from the source and caches it if not found. Handles potential exceptions during cache operations. ```csharp public class CacheLayer { private readonly FullRedis _redis; public CacheLayer() { _redis = new FullRedis("127.0.0.1:6379", null, 0); } public T GetOrFetch(string key, Func fetch, int expire = 3600) { try { var cached = _redis.Get(key); if (cached != null) return cached; } catch { } var value = fetch(); try { _redis.Set(key, value, expire); } catch { } return value; } } ``` -------------------------------- ### Basic Redis Operations: Set, Get, Add, Replace, Increment, Decrement Source: https://github.com/newlifex/newlife.redis/blob/master/Readme.MD Illustrates fundamental Redis operations including setting and getting values with expiration, adding keys only if they don't exist, replacing values, and performing atomic increments and decrements. ```csharp // 写入 / 读取 ds.Set("k1", 123, expire: 600); var v = rds.Get("k1"); // 仅在不存在时写入 var ok = rds.Add("k2", "init"); // 替换并返回旧值 var old = rds.Replace("k2", "new"); // 计数器 ds.Increment("counter", 1); ds.Decrement("counter", 2); ``` -------------------------------- ### Query Queue Status API Response Example Source: https://github.com/newlifex/newlife.redis/blob/master/Doc/RedisSwitch项目说明.md Example JSON response for querying the current status of the message queue. ```json { "queueLength": 5, "timestamp": "2026-02-15T12:30:00" } ``` -------------------------------- ### Implementing a Cache Service with ICache Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/dependency-injection.md Shows how to create a CacheService that utilizes the ICache interface for generic caching operations like GetOrAdd, Set, and Get. ```csharp public class CacheService { private readonly ICache _cache; public CacheService(ICache cache) { _cache = cache; } public T GetOrAdd(string key, Func factory, int expire = 3600) { var value = _cache.Get(key); if (value != null) return value; value = factory(); _cache.Set(key, value, expire); return value; } public void Set(string key, T value, int expire = 3600) { _cache.Set(key, value, expire); } public T? Get(string key) { return _cache.Get(key); } } // Usage services.AddScoped(); services.AddRedis("server=localhost:6379"); ``` -------------------------------- ### Bind Redis Configuration from appsettings.json Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/configuration.md Example of binding Redis configuration from an appsettings.json file to RedisOptions using IConfigProvider in ASP.NET Core's Startup.cs or Program.cs. ```json // appsettings.json { "Redis": { "Server": "127.0.0.1:6379", "Password": "mypass", "Db": 3, "Timeout": 5000 } } ``` ```csharp // Startup.cs / Program.cs services.AddSingleton(sp => { var options = new RedisOptions(); var config = sp.GetRequiredService(); config.Bind(options, false, "Redis"); return new FullRedis(options); }); ``` -------------------------------- ### FullRedis Prefix Support Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/INDEX.md Configure a prefix for all keys managed by a FullRedis instance to logically separate data. This example shows setting the prefix and how a key is stored. ```csharp var redis = new FullRedis("127.0.0.1:6379") { Prefix = "app:" }; redis.Set("key", "value"); // Actually stored as "app:key" ``` -------------------------------- ### Configure Cloud Provider Connection Strings Source: https://github.com/newlifex/newlife.redis/blob/master/Doc/架构文档.md Provides connection string examples for various cloud Redis services. Includes configurations for Aliyun KVStore (Standard, Cluster, ACL, SSL) and Huawei DCS (Master-Slave, SSL, Cluster). ```text 阿里云 KVStore(标准版): ``` server=xxxxxx.redis.rds.aliyuncs.com:6379;password=YourPassword;db=0 ``` 阿里云 KVStore(集群版): ``` server=xxxxxx.redis.rds.aliyuncs.com:6379;password=YourPassword;db=0 // AutoDetect=false(默认),代理层透明处理分片 ``` 阿里云 KVStore(Redis 6.0 ACL): ``` server=xxxxxx.redis.rds.aliyuncs.com:6379;username=YourUser;password=YourPassword;db=0 ``` 腾讯云 Redis(标准/集群版): ``` server=xxxxxx.redis.tencentcds.com:6379;username=instanceId;password=YourPassword;db=0 // 注意:腾讯云使用 AUTH instanceId:password 格式 ``` 华为云 DCS(主备版): ``` server=xxxxxx.dcs.myhuaweicloud.com:6379;password=YourPassword;db=0 ``` 华为云 DCS(集群版注意事项): ```csharp // 集群版不支持 SELECT,Db 必须为 0 // AutoDetect = false(默认),避免获取内网节点地址 var rds = new FullRedis("xxxxxx.dcs.myhuaweicloud.com:6379", "password", 0); // 注意:Db = 0,不可使用 SELECT 切库 ``` ``` -------------------------------- ### Serialization Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/api-reference.md Explains how objects are serialized using IPacketEncoder and provides an example for custom encoders. ```APIDOC ## Serialization Objects are serialized using `IPacketEncoder`. Default implementation uses JSON via `Encoder` property. Custom encoder example: ```csharp redis.Encoder = new MyCustomEncoder(); ``` ``` -------------------------------- ### Publish Message using PowerShell Source: https://github.com/newlifex/newlife.redis/blob/master/Doc/RedisSwitch项目说明.md PowerShell script example for publishing a message to the RedisSwitch API. ```powershell $body = @{ content = "测试消息" properties = @{ userId = "12345" action = "login" } } | ConvertTo-Json Invoke-RestMethod -Uri "http://localhost:5000/api/message/publish" ` -Method Post ` -Body $body ` -ContentType "application/json" ``` -------------------------------- ### Redis Hash Operations: Set, Get, GetAll Source: https://github.com/newlifex/newlife.redis/blob/master/Readme.MD Demonstrates how to interact with Redis Hashes, including setting individual fields, retrieving field values, and fetching all fields and values within a hash. ```csharp var hash = rds.GetDictionary("user:1001"); hash["Name"] = "Alice"; hash["Email"] = "alice@example.com"; var name = hash["Name"]; var all = hash.GetAll(); ``` -------------------------------- ### Basic Redis Operations (Set, Get, Remove) Source: https://github.com/newlifex/newlife.redis/blob/master/Readme.en.md Demonstrates setting a user object, retrieving it, checking existence, and removing it from Redis. Uses JSON serialization by default for complex objects. ```csharp var rds = new FullRedis("127.0.0.1", null, 7); rds.Log = XTrace.Log; rds.ClientLog = XTrace.Log; // Debug log. Comment out for production use. var user = new User { Name = "NewLife", CreateTime = DateTime.Now }; ds.Set("user", user, 3600); var user2 = rds.Get("user"); XTrace.WriteLine("Json: {0}", user2.ToJson()); XTrace.WriteLine("Json: {0}", rds.Get("user")); if (rds.ContainsKey("user")) XTrace.WriteLine("Exists!"); rds.Remove("user"); ``` -------------------------------- ### Redis Hash Basic Operations Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/api-reference.md Shows how to set, get, check for existence, retrieve all fields, and increment values in a Redis hash. Also demonstrates removing and clearing fields. ```csharp var redis = new FullRedis("127.0.0.1:6379"); var hash = redis.GetDictionary("user:1"); // Set fields hash["name"] = "John"; hash["email"] = "john@example.com"; // Get field var name = hash["name"]; // Check field exists if (hash.ContainsKey("email")) { } // Get all fields var all = hash.GetAll(); foreach (var field in hash.Keys) { } // Increment var counters = redis.GetDictionary("stats"); counters.HIncrBy("views", 1); // Delete hash.Remove("email"); hash.Clear(); ``` -------------------------------- ### Injecting FullRedis into ASP.NET Core Controller Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/dependency-injection.md Provides an example of constructor injection for FullRedis in an ASP.NET Core controller, demonstrating how to retrieve and use cached data. ```csharp [ApiController] [Route("api/[controller]")] public class CacheController : ControllerBase { private readonly FullRedis _redis; // Constructor injection public CacheController(FullRedis redis) { _redis = redis; } [HttpGet("{key}")] public IActionResult Get(string key) { var value = _redis.Get(key); if (value == null) return NotFound(); return Ok(value); } [HttpPost] public IActionResult Set(string key, [FromBody] string value) { _redis.Set(key, value, 3600); return Ok(); } } ``` -------------------------------- ### Setting and Getting Expiration Times Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/api-reference.md Demonstrates how to set a time-to-live (TTL) for a key using TimeSpan and retrieve the remaining TTL. This is crucial for managing cache data. ```csharp // Expiration redis.SetExpire("key1", TimeSpan.FromHours(1)); var ttl = redis.GetExpire("key1"); ``` -------------------------------- ### Basic Try-Catch for Network Operations Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/errors.md A fundamental example demonstrating the use of try-catch blocks to handle potential Redis exceptions during network operations. ```csharp try { var value = redis.Get("key"); } catch (RedisException ex) { // Handle error } ``` -------------------------------- ### Redis Set Advanced Methods Example Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/api-reference.md Demonstrates advanced set operations like SAdd for batch additions, checking membership with Contains, retrieving all members with GetAll, and performing set operations such as Inter, Union, and Diff. ```csharp var redis = new FullRedis("127.0.0.1:6379"); var set = redis.GetSet("tags"); // Add members set.Add("redis"); set.Add("database"); var count = set.SAdd("cache", "queue", "message"); // Check membership if (set.Contains("redis")) { } // Get all var tags = set.GetAll(); // Set operations var other = redis.GetSet("tags2"); var intersection = set.Inter("tags2"); var union = set.Union("tags2"); var diff = set.Diff("tags2"); ``` -------------------------------- ### ASP.NET Core Redis Setup Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/INDEX.md Configure NewLife.Redis services in ASP.NET Core by setting server details and optionally password and database. The configured Redis instance can then be injected into controllers. ```csharp // Program.cs var builder = WebApplication.CreateBuilder(args); builder.Services.AddRedis(options => { options.Server = "localhost:6379"; options.Password = "mypass"; options.Db = 0; }); var app = builder.Build(); app.Run(); // In controller [ApiController] public class CacheController { public CacheController(FullRedis redis) { _redis = redis; } } ``` -------------------------------- ### Redis Sorted Set Advanced Methods Example Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/api-reference.md Illustrates advanced sorted set operations including adding members with scores, retrieving ranges with scores, filtering by score, incrementing scores, and retrieving rank. Also shows popping the highest and lowest scored members. ```csharp var redis = new FullRedis("127.0.0.1:6379"); var leaderboard = redis.GetSortedSet("scores"); // Add members with scores leaderboard.Add("player1", 100.0); leaderboard.Add("player2", 95.5); // Get top 10 var top = leaderboard.Range(0, 9); var topWithScores = leaderboard.RangeWithScores(0, 9); // Get by score range var good = leaderboard.RangeByScore(90.0, 100.0, 0, 10); // Increment score leaderboard.Increment("player1", 5.0); // Get rank var rank = leaderboard.Rank("player1"); // Pop highest var winners = leaderboard.PopMax(3); ``` -------------------------------- ### Redis Helper Singleton Instance Source: https://github.com/newlifex/newlife.redis/blob/master/Readme.en.md Demonstrates how to set up a singleton Redis instance using a helper class. The default connection string and password can be customized. ```csharp public static class RedisHelper { /// /// Redis instance /// public static FullRedis redisConnection { get; set; } = new FullRedis("127.0.0.1:6379", "123456", 4); } Console.WriteLine(RedisHelper.redisConnection.Keys); ``` -------------------------------- ### Pipelining for Batch Operations Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/INDEX.md Improve performance by batching multiple Redis commands using pipelining. Start the pipeline, execute commands, and then stop the pipeline to get results. ```csharp redis.StartPipeline(); redis.Set("key1", "value1"); redis.Set("key2", "value2"); var results = redis.StopPipeline(true); ``` -------------------------------- ### Initialize Redis Client with Init Method Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/configuration.md Use the Init method to configure an existing FullRedis instance with connection details from a string. ```csharp // Using Init method var redis = new FullRedis(); redis.Init("server=127.0.0.1:6379;password=pass;db=3;timeout=3000"); ``` -------------------------------- ### Publish Message API Success Response Example Source: https://github.com/newlifex/newlife.redis/blob/master/Doc/RedisSwitch项目说明.md Example JSON response indicating a successful message publication. ```json { "success": true, "messageId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "errorMessage": null } ``` -------------------------------- ### FullRedis Initialization with Options Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/api-reference.md Configure and initialize the FullRedis client using a `RedisOptions` object for detailed settings. ```csharp var options = new RedisOptions { Server = "127.0.0.1:6379", Password = "pass", Db = 3, Prefix = "app:" }; var redis = new FullRedis(options); ``` -------------------------------- ### Instantiate Redis Client Source: https://github.com/newlifex/newlife.redis/blob/master/Readme.en.md Shows different ways to instantiate the FullRedis client, including specifying the server, password, and database. It also demonstrates setting a custom logger. ```csharp // Instantiate Redis, default port 6379 can be omitted, two ways to write the password //var rds = new FullRedis("127.0.0.1", null, 7); var rds = new FullRedis("127.0.0.1:6379", "pass", 7); //var rds = new FullRedis(); //rds.Init("server=127.0.0.1:6379;password=pass;db=7"); rds.Log = XTrace.Log; ``` -------------------------------- ### FullRedis Constructors Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/api-reference.md Demonstrates various ways to instantiate the FullRedis client, including default, connection string, options, and service provider configurations. ```csharp public FullRedis() public FullRedis(String server, String password, Int32 db) public FullRedis(String server, String userName, String password, Int32 db) public FullRedis(RedisOptions options) public FullRedis(IServiceProvider provider, String name) public FullRedis(IServiceProvider provider, RedisOptions options) ``` -------------------------------- ### Publish Message API Failure Response Example Source: https://github.com/newlifex/newlife.redis/blob/master/Doc/RedisSwitch项目说明.md Example JSON response indicating a failed message publication due to validation errors. ```json { "success": false, "messageId": null, "errorMessage": "消息内容不能为空" } ``` -------------------------------- ### Registering User and Cache Services Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/dependency-injection.md Demonstrates registering IUserRepository and IUserService with their concrete implementations, along with the AddRedis extension method for service configuration. ```csharp public interface IUserService { User GetUser(int id); void CacheUser(User user); } public class UserService : IUserService { private readonly ICache _cache; private readonly IUserRepository _repository; public UserService(ICache cache, IUserRepository repository) { _cache = cache; _repository = repository; } public User GetUser(int id) { var cacheKey = $"user:{id}"; // Try cache first var user = _cache.Get(cacheKey); if (user != null) return user; // Get from database user = _repository.GetById(id); // Cache for 1 hour _cache.Set(cacheKey, user, 3600); return user; } public void CacheUser(User user) { _cache.Set($"user:{user.Id}", user, 3600); } } // Register services.AddScoped(); services.AddScoped(); services.AddRedis("server=localhost:6379"); ``` -------------------------------- ### Simple Redis Constructor Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/configuration.md Instantiate a FullRedis client with basic connection details like server address, password, and database number. ```csharp // Simple constructor var redis = new FullRedis("127.0.0.1:6379", "password", 0); ``` -------------------------------- ### Redis Hash Advanced Methods Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/api-reference.md Offers advanced methods for Redis hashes, including deleting fields, retrieving multiple fields, setting multiple fields, getting all fields, incrementing numeric fields, setting fields conditionally, getting field lengths, and searching with patterns. ```APIDOC ## Redis Hash Advanced Methods ### Description Offers advanced methods for Redis hashes, including deleting fields, retrieving multiple fields, setting multiple fields, getting all fields, incrementing numeric fields, setting fields conditionally, getting field lengths, and searching with patterns. ### Methods - **HDel** `(params fields: TKey[])` - Delete fields. Returns `Int32`. - **HMGet** `(params fields: TKey[])` - Get multiple fields. Returns `TValue[]?`. - **HMSet** `(keyValues: IEnumerable)` - Set multiple fields. Returns `Boolean`. - **GetAll** `()` - Get all fields. Returns `IDictionary`. - **HIncrBy** `(field: TKey, value: Int64)` - Increment int field. Returns `Int64`. - **HIncrBy** `(field: TKey, value: Double)` - Increment double field. Returns `Double`. - **HSetNX** `(field: TKey, value: TValue)` - Set if not exists. Returns `Int32`. - **HStrLen** `(field: TKey)` - Get field value length. Returns `Int32`. - **Search** `(pattern: String, count: Int32)` - Search with pattern. Returns `IEnumerable`. ``` -------------------------------- ### Batch Operations (SetAll, GetAll) Source: https://github.com/newlifex/newlife.redis/blob/master/Readme.en.md Shows how to set multiple key-value pairs and retrieve multiple values simultaneously using SetAll and GetAll for improved throughput. ```csharp var rds = new FullRedis("127.0.0.1", null, 7); rds.Log = XTrace.Log; rds.ClientLog = XTrace.Log; // Debug log. Comment out for production use. var dic = new Dictionary { ["name"] = "NewLife", ["time"] = DateTime.Now, ["count"] = 1234 }; rds.SetAll(dic, 120); var vs = rds.GetAll(dic.Keys); XTrace.WriteLine(vs.Join(",", e => $"{e.Key}={e.Value}")); ``` -------------------------------- ### Creating a CacheFactory with ICacheProvider Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/dependency-injection.md Illustrates how to use ICacheProvider to obtain an ICache instance or a producer-consumer queue. Registration of RedisCacheProvider is also shown. ```csharp public class CacheFactory { private readonly ICacheProvider _provider; public CacheFactory(ICacheProvider provider) { _provider = provider; } public ICache GetCache() { return _provider.Cache; } public IProducerConsumer GetQueue(string key) { return _provider.GetQueue(key); } } // Register services.AddRedisCacheProvider(); services.AddScoped(); ``` -------------------------------- ### Custom Serialization Encoder Example Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/api-reference.md Shows how to set a custom encoder for object serialization in Redis. ```csharp redis.Encoder = new MyCustomEncoder(); ``` -------------------------------- ### Configure SSL Encrypted Redis Connection (Aliyun) Source: https://github.com/newlifex/newlife.redis/blob/master/Doc/架构文档.md Demonstrates how to establish an SSL-encrypted connection to Aliyun KVStore using FullRedis. Requires specifying the SSL protocol and providing a certificate. ```csharp var rds = new FullRedis("xxxxxx.redis.rds.aliyuncs.com:6380", "password", 0) { SslProtocol = SslProtocols.Tls12, Certificate = new X509Certificate2("aliyun-redis.pem") }; ``` -------------------------------- ### Binding Redis Configuration from Configuration Center Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/dependency-injection.md Demonstrates retrieving and binding Redis options from a configuration service using IConfigProvider. ```csharp // Get from configuration service var config = serviceProvider.GetService(); var options = new RedisOptions(); config?.Bind(options, false, "Redis"); services.AddRedis(options); ``` -------------------------------- ### Target API MessageData Model Example Source: https://github.com/newlifex/newlife.redis/blob/master/Doc/RedisSwitch项目说明.md JSON structure expected by the target API for receiving messages. ```json { "id": "消息ID", "content": "消息内容", "createdTime": "2026-02-15T12:00:00", "properties": { "key1": "value1", "key2": "value2" } } ``` -------------------------------- ### Create Redis Client from Connection String Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/configuration.md Initialize a FullRedis client using a standard connection string format. ```csharp // Standard format var redis = FullRedis.Create("server=127.0.0.1:6379;password=123456;db=3"); ``` -------------------------------- ### Core Redis Operations Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/api-reference.md Provides methods for basic Redis operations such as getting, setting, adding, replacing, incrementing, decrementing, and removing keys. ```APIDOC ## Core Redis Operations ### Description Provides methods for basic Redis operations such as getting, setting, adding, replacing, incrementing, decrementing, and removing keys. ### Methods - **Get** - Signature: `(key: String)` - Returns: `T?` - Description: Get value by key. - **Set** - Signature: `(key: String, value: T, expire: Int32)` - Returns: `void` - Description: Set value with expiration. - **Add** - Signature: `(key: String, value: T, expire: Int32)` - Returns: `Boolean` - Description: Add if not exists. - **Replace** - Signature: `(key: String, value: T)` - Returns: `Object?` - Description: Replace and return old value. - **Increment** - Signature: `(key: String, value: Int64)` - Returns: `Int64` - Description: Increment value. - **Decrement** - Signature: `(key: String, value: Int64)` - Returns: `Int64` - Description: Decrement value. - **Remove** - Signature: `(params keys: String[])` - Returns: `Int32` - Description: Remove keys, returns count. - **RemoveAll** - Signature: `()` - Returns: `void` - Description: Clear all keys. - **ContainsKey** - Signature: `(key: String)` - Returns: `Boolean` - Description: Check if key exists. - **Exists** - Signature: `(params keys: String[])` - Returns: `Int32` - Description: Count existing keys. - **SetExpire** - Signature: `(key: String, expire: TimeSpan)` - Returns: `Boolean` - Description: Set expiration time. - **GetExpire** - Signature: `(key: String)` - Returns: `TimeSpan` - Description: Get time to live. - **Scan** - Signature: `(pattern: String, count: Int32)` - Returns: `IEnumerable` - Description: Scan keys with pattern. - **Keys** - Signature: `()` - Returns: `String[]` - Description: Get all keys. - **GetAll** - Signature: `(keys: IEnumerable)` - Returns: `IDictionary` - Description: Get multiple values. - **SetAll** - Signature: `(values: IDictionary, expire: Int32)` - Returns: `void` - Description: Set multiple values. ``` -------------------------------- ### Get Stream Groups Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/types.md Retrieves all consumer groups for a given Redis stream. Useful for monitoring group status and pending message counts. ```csharp var stream = redis.GetStream("messages"); var groups = stream.GetGroups(); foreach (var group in groups) { Console.WriteLine($"Group: {group.Name}, Pending: {group.Pending}"); } ``` -------------------------------- ### Initialize Redis from Environment Variables Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/configuration.md Initializes the Redis client by reading configuration from environment variables. Environment variables should follow the pattern `Redis_{Name}`. ```csharp // Set environment variable Environment.SetEnvironmentVariable("Redis_MyCache", "server=127.0.0.1:6379;password=pass;db=0"); // Initialize from env var var redis = new FullRedis("MyCache"); ``` -------------------------------- ### Create FullRedis Instance from Connection String Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/api-reference.md Use the static `Create` method to instantiate a FullRedis client using a connection string. ```csharp var redis = FullRedis.Create("server=127.0.0.1:6379;password=123456;db=3"); ``` -------------------------------- ### Basic Redis Registration in ASP.NET Core Program.cs Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/dependency-injection.md Demonstrates basic Redis registration in an ASP.NET Core application's Program.cs file, either from a connection string or configuration options. ```csharp var builder = WebApplication.CreateBuilder(args); // Register Redis from connection string builder.Services.AddRedis("server=redis:6379;password=mypass;db=0"); // Or from configuration builder.Services.AddRedis(options => { options.Server = builder.Configuration["Redis:Server"]; options.Password = builder.Configuration["Redis:Password"]; options.Db = int.Parse(builder.Configuration["Redis:Db"] ?? "0"); }); var app = builder.Build(); app.Run(); ``` -------------------------------- ### Basic FullRedis Operations Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/api-reference.md Perform basic Redis operations like setting a value with expiration, getting a value, and removing a key using the FullRedis client. ```csharp // Basic initialization var redis = new FullRedis("127.0.0.1:6379", "password", 0); // Basic operations redis.Set("user:1", new { Name = "John" }, 3600); var user = redis.Get("user:1"); redis.Remove("user:1"); ``` -------------------------------- ### Redis Client Creation with Connection String Source: https://github.com/newlifex/newlife.redis/blob/master/Readme.MD Creates a FullRedis client instance using a connection string format. This is recommended when using a configuration center. ```csharp var rds = FullRedis.Create("server=127.0.0.1:6379;password=pass;db=0;timeout=3000"); ``` -------------------------------- ### Get Stream Pending Messages Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/types.md Retrieves information about pending messages for a specific consumer group in a Redis stream. Useful for understanding message backlog and distribution. ```csharp var stream = redis.GetStream("messages"); var pending = stream.GetPending("group1"); Console.WriteLine($"Total pending: {pending.Count}"); foreach (var consumer in pending.Consumers) { Console.WriteLine($"{consumer.Key}: {consumer.Value} pending"); } ``` -------------------------------- ### Redis Registration with appsettings.json in ASP.NET Core Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/dependency-injection.md Shows how to configure Redis connection details in appsettings.json and bind them to Redis options in Program.cs for registration. ```json { "Redis": { "Server": "localhost:6379", "Password": "mypassword", "Db": 0, "Timeout": 3000, "Prefix": "myapp:" } } ``` ```csharp builder.Services.AddRedis(options => builder.Configuration.GetSection("Redis").Bind(options) ); ``` -------------------------------- ### Safe Type Handling for Redis Get Operations Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/errors.md Demonstrates safe ways to retrieve and use data of expected types from Redis, avoiding potential runtime errors. ```csharp // Unsafe - wrong type var num = redis.Get("stringkey"); // May fail // Safe - check first var value = redis.Get("key"); if (int.TryParse(value, out var num)) { // Use num } // Safe - use dynamic dynamic obj = redis.Get("key"); ``` -------------------------------- ### Get Stream Consumers Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/types.md Retrieves information about consumers within a specific consumer group for a Redis stream. Useful for inspecting individual consumer status and pending messages. ```csharp var stream = redis.GetStream("messages"); var consumers = stream.GetConsumers("group1"); foreach (var consumer in consumers) { Console.WriteLine($"Consumer: {consumer.Name}, Pending: {consumer.Pending}"); } ``` -------------------------------- ### Registering Multiple Named Redis Instances Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/dependency-injection.md Demonstrates registering multiple Redis instances with distinct names (e.g., 'cache', 'session', 'queue') for different purposes. Retrieval in a controller shows how to access the last registered instance by default. ```csharp // Cache Redis services.AddRedis("cache", "server=cache-redis:6379;db=0"); // Session Redis services.AddRedis("session", "server=session-redis:6379;db=1"); // Queue Redis services.AddRedis("queue", "server=queue-redis:6379;db=2"); // Retrieve in controller public class MyController : ControllerBase { private readonly FullRedis _cacheRedis; public MyController(FullRedis redis) { _cacheRedis = redis; // Gets last registered } } ``` -------------------------------- ### Basic Redis Operations Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/INDEX.md Demonstrates basic string, list, hash, set, sorted set, queue, and stream operations using the FullRedis client. Includes setting values, retrieving data, adding elements, and taking items from queues and streams. ```csharp // Create instance var redis = new FullRedis("127.0.0.1:6379", "password", 0); // String operations redis.Set("key", "value", 3600); var value = redis.Get("key"); redis.Remove("key"); // List operations var list = redis.GetList("mylist"); list.Add("item1"); list.AddRange(new[] { "item2", "item3" }); // Hash operations var hash = redis.GetDictionary("myhash"); hash["field"] = "value"; var val = hash["field"]; // Set operations var set = redis.GetSet("myset"); set.Add("member1"); var members = set.GetAll(); // Sorted set operations var zset = redis.GetSortedSet("myzset"); zset.Add("member1", 100.0); var top = zset.Range(0, 9); // Queue operations var queue = redis.GetQueue("tasks"); queue.Add("task1"); var task = queue.TakeOne(); // Stream operations var stream = redis.GetStream("messages"); stream.SetGroup("group1"); var msgId = stream.Add("message"); var msg = stream.TakeOne(); ``` -------------------------------- ### Configure Redis Operation Timeouts Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/errors.md Set custom timeouts for Redis operations to prevent long-running requests from blocking the application. Includes examples for general timeout and blocking queue operations. ```csharp // Increase timeout for slow operations redis.Timeout = 5000; // 5 seconds // Blocking operations var item = queue.TakeOne(timeout: 30); // Block up to 30s ``` -------------------------------- ### Configure Multiple Redis Instances Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/dependency-injection.md Set up distinct Redis clients for caching, sessions, and queues by registering them with unique names. Services can then inject specific instances. ```csharp var builder = WebApplication.CreateBuilder(args); // Cache Redis var cacheRedis = builder.Services.AddRedis( "cache", "server=cache-redis:6379;db=0" ); // Session Redis var sessionRedis = builder.Services.AddRedis( "session", "server=session-redis:6379;db=1" ); // Queue Redis var queueRedis = builder.Services.AddRedis( "queue", "server=queue-redis:6379;db=2" ); // Register services builder.Services.AddScoped(); builder.Services.AddScoped(); var app = builder.Build(); // Services receive primary (last registered) FullRedis by default // Or inject specific instance by registering named factories ``` -------------------------------- ### Configure Redis Caching and Data Protection Source: https://github.com/newlifex/newlife.redis/blob/master/Doc/架构文档.md Example of configuring Redis caching and data protection services in Program.cs. It shows how to set up connection options for caching and integrate data protection with Redis. ```csharp builder.Services.AddRedisCaching(options => { options.Server = "127.0.0.1:6379"; options.Password = "pass"; options.Db = 0; options.Prefix = "myapp:"; }); // 同时注册 IDistributedCache + FullRedis builder.Services.AddDataProtection() .PersistKeysToRedis(redis, "DataProtection-Keys"); ``` -------------------------------- ### Binding Redis Configuration from appsettings.json Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/dependency-injection.md Shows how to bind Redis configuration section from appsettings.json to Redis options using the Bind method. ```csharp services.AddRedis(options => { var config = builder.Configuration.GetSection("Redis"); config.Bind(options); }); ``` -------------------------------- ### Batch Redis Operations: SetAll and GetAll Source: https://github.com/newlifex/newlife.redis/blob/master/Readme.MD Shows how to perform batch write operations using a dictionary and batch read operations for multiple keys, both with optional expiration. ```csharp // 批量读写 ds.SetAll(new Dictionary { ["a"] = 1, ["b"] = 2 }, expire: 300); var dict = rds.GetAll(["a", "b"]); ``` -------------------------------- ### Redis List Operations: Add, Get, RightPop Source: https://github.com/newlifex/newlife.redis/blob/master/Readme.MD Illustrates basic operations on Redis Lists, including adding elements to the end, retrieving elements by index, and removing elements from the right end. ```csharp var list = rds.GetList("queue:demo"); list.Add("job1"); list.Add("job2"); var first = list[0]; var popped = list.RightPop(); ``` -------------------------------- ### Validate Redis Connection on Startup Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/errors.md Verify the Redis connection immediately after instantiation using a Ping command. This helps catch configuration errors early. ```csharp var redis = new FullRedis("127.0.0.1:6379", "pass", 0); // Verify connection immediately try { redis.Ping(); // Test connectivity } catch (RedisException ex) { Console.WriteLine($"Connection failed: {ex.Message}"); throw; } ``` -------------------------------- ### Handling Wrong Type Command Errors Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/errors.md Catch RedisException when the message contains 'WRONGTYPE', indicating an operation was applied to a key with an incompatible data type. This example shows attempting a list operation on a string key. ```csharp try { redis.Set("mylist", "string_value"); var list = redis.GetList("mylist"); list.Add("item"); // WRONGTYPE error } catch (RedisException ex) when (ex.Message.Contains("WRONGTYPE")) { Console.WriteLine("Wrong data type for this operation"); } ``` -------------------------------- ### Handling Key Not Found Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/errors.md Accessing a non-existent key with Get() returns null. For collections like lists or dictionaries, it returns an empty collection. The TryGetValue method provides a safe way to check for key existence. ```csharp var value = redis.Get("nonexistent"); if (value == null) { Console.WriteLine("Key not found"); } // Safe access with TryGetValue var hash = redis.GetDictionary("myhash"); if (hash.TryGetValue("field", out var val)) { // Use val } ``` -------------------------------- ### Checking Key Existence and Counting Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/api-reference.md Illustrates how to check if a key exists and count multiple existing keys. This is useful for validating data presence before operations. ```csharp // Check existence if (redis.ContainsKey("key1")) { } int count = redis.Exists("key1", "key2", "key3"); ``` -------------------------------- ### Handle Data Decoding Errors Source: https://github.com/newlifex/newlife.redis/blob/master/_autodocs/errors.md Catch RedisException or other serialization exceptions when data cannot be decoded to the target type. This can occur due to corrupted data, incorrect type specification in Get(), or encoding mismatches. Use dynamic or object for unknown types. ```csharp try { var data = redis.Get("stringkey"); // Type mismatch } catch (RedisException ex) { Console.WriteLine($"Decode error: {ex.Message}"); } // Use dynamic or object for unknown types var obj = redis.Get("key"); ``` -------------------------------- ### Configure Tencent Cloud Redis Connection (Code) Source: https://github.com/newlifex/newlife.redis/blob/master/Doc/架构文档.md Shows how to instantiate FullRedis for Tencent Cloud Redis, handling the specific authentication format. The library automatically uses the AUTH userName password format. ```csharp var rds = new FullRedis("xxxxxx.redis.tencentcds.com:6379", "instanceId", "password", 0); ```