CSRedis

repository·master·Indexed 24 days ago

https://github.com/2881099/csredis

A high-performance Redis client for .NET that maintains method name consistency with redis-cli. It supports Single Machine, Sentinel, and Cluster deployment modes. The library provides high-level abstractions such as CacheShell, pipeline support via StartPipe, and integration with .NET's IDistributedCache through the Caching.CSRedis package. Key features include connection pooling, SSL support, and extension methods for object serialization in distributed caching.

Tokens
3.1K
Snippets
13
Records
14
Agent score
35%

What's inside CSRedis

  1. Configure Redis Cluster

    master

    In 'Normal Mode', define a CSRedisClient with a standard connection string. The client will automatically update its Nodes property by recording slots from MOVED or ASK errors returned by the server.

    Important Constraints:

    • Prefix Warning: Do NOT set a prefix (or ensure all clients have the same prefix) when using Cluster mode alongside 'Partition Mode'. Doing so causes keySlot calculations to mismatch the server, preventing slot caching.
    • Feature Limitations: Official Redis Cluster does not support multi-key commands, Pipeline, or Eval (scripts).
  2. Install CSRedisCore and Caching.CSRedis

    master

    To use the core Redis client, install CSRedisCore via NuGet. To use the IDistributedCache implementation, install Caching.CSRedis.

    dotnet add package CSRedisCore
    dotnet add package Caching.CSRedis
    dotnet add package CSRedisCore
  3. Configure CSRedis in Standard Mode

    master

    To use CSRedis in a standard (single machine) configuration, instantiate a CSRedis.CSRedisClient with a connection string and register it as a singleton IDistributedCache in your service collection.

    The connection string supports parameters such as password, defaultDatabase, ssl, writeBuffer, poolsize, and prefix.

    var csredis = new CSRedis.CSRedisClient("127.0.0.1:6379,password=123,defaultDatabase=13,ssl=false,writeBuffer=10240,poolsize=50,prefix=key前辍");
    services.AddSingleton<IDistributedCache>(new Microsoft.Extensions.Caching.Redis.CSRedisCache(csredis));
  4. Configure CSRedis in Cluster Mode

    master

    To use CSRedis in Cluster mode, instantiate CSRedis.CSRedisClient by passing null as the first argument (likely representing a master/seed node or specific cluster config) followed by multiple connection strings for the cluster nodes. Each node can have its own defaultDatabase, poolsize, and prefix settings.

    var csredis = new CSRedis.CSRedisClient(null,
      "127.0.0.1:6371,password=123,defaultDatabase=11,poolsize=10,ssl=false,writeBuffer=10240,prefix=key前辍", 
      "127.0.0.1:6372,password=123,defaultDatabase=12,poolsize=11,ssl=false,writeBuffer=10240,prefix=key前辍",
      "127.0.0.1:6373,password=123,defaultDatabase=13,poolsize=12,ssl=false,writeBuffer=10240,prefix=key前辍",
      "127.0.0.1:6374,password=123,defaultDatabase=14,poolsize=13,ssl=false,writeBuffer=10240,prefix=key前辍");
    services.AddSingleton<IDistributedCache>(new Microsoft.Extensions.Caching.Redis.CSRedisCache(csredis));
  5. Integrate with IDistributedCache

    master

    Use the Caching.CSRedis package to integrate with .NET's IDistributedCache interface.

    1. Initialize the static RedisHelper with your CSRedisClient instance.
    2. Register the CSRedisCache as a singleton in your service collection.

    Note: CSRedisClient should be treated as a singleton, and using the static RedisHelper is recommended.

    // 1. Initialization
    RedisHelper.Initialization(csredis);
    
    // 2. Dependency Injection registration
    services.AddSingleton<IDistributedCache>(new Microsoft.Extensions.Caching.Redis.CSRedisCache(RedisHelper.Instance));
    
    // 3. Usage
    RedisHelper.Set("test1", "123123", 60);
    var val = RedisHelper.Get("test1");
    RedisHelper.Initialization(csredis);
    services.AddSingleton<IDistributedCache>(new Microsoft.Extensions.Caching.Redis.CSRedisCache(RedisHelper.Instance));
  6. Use Subscribe and Publish

    master

    CSRedis supports both standard Subscribe and pattern-based PSubscribe methods. The implementation handles node matching in partitioned environments to ensure messages are not executed multiple times across nodes.

    Standard Subscription:

    RedisHelper.Subscribe(
      ("chan1", msg => Console.WriteLine(msg.Body)),
      ("chan2", msg => Console.WriteLine(msg.Body)));

    Pattern Subscription:

    RedisHelper.PSubscribe(new[] { "test*", "*test001", "test*002" }, msg => {
      Console.WriteLine($"PSUB   {msg.MessageId}:{msg.Body}    {msg.Pattern}: chan:{msg.Channel}");
    });

    Publishing:

    RedisHelper.Publish("chan1", "123123123");
    //Native subscribe
    RedisHelper.Subscribe(
      ("chan1", msg => Console.WriteLine(msg.Body)),
      ("chan2", msg => Console.WriteLine(msg.Body)));
    
    //Pattern subscribe
    RedisHelper.PSubscribe(new[] { "test*", "*test001", "test*002" }, msg => {
      Console.WriteLine($"PSUB   {msg.MessageId}:{msg.Body}    {msg.Pattern}: chan:{msg.Channel}");
    });
    
    //Publish
    RedisHelper.Publish("chan1", "123123123");
  7. Use CacheShell for simplified caching logic

    master

    The CacheShell method simplifies the common pattern of: checking a cache, deserializing, handling errors, fetching from a source on miss, and then saving back to cache.

    Basic usage (string/hash):

    // Fetches from source and caches for 10 seconds
    var t1 = RedisHelper.CacheShell("test1", 10, () => Test.Select.WhereId(1).ToOne());

    Usage with complex keys:

    // Using a key and a sub-key
    var t2 = RedisHelper.CacheShell("test", "1", 10, () => Test.Select.WhereId(1).ToOne());
    
    // Fetching multiple items at once
    var t3 = RedisHelper.CacheShell("test", new [] { "1", "2" }, 10, notCacheFields => new [] {
      ("1", Test.Select.WhereId(1).ToOne()),
      ("2", Test.Select.WhereId(2).ToOne())
    });
    //使用缓存壳效果同上,以下示例使用 string 和 hash 缓存数据
    var t1 = RedisHelper.CacheShell("test1", 10, () => Test.Select.WhereId(1).ToOne());
    var t2 = RedisHelper.CacheShell("test", "1", 10, () => Test.Select.WhereId(1).ToOne());
    var t3 = RedisHelper.CacheShell("test", new [] { "1", "2" }, 10, notCacheFields => new [] {
      ("1", Test.Select.WhereId(1).ToOne()),
      ("2", Test.Select.WhereId(2).ToOne())
    });
  8. Use Cache Object Extension Methods

    master

    The library provides extension methods for IDistributedCache to simplify working with complex objects instead of raw byte arrays or strings.

    • SetObject(string key, object value): Serializes and stores an object.
    • GetObject(string key): Retrieves an object as a generic object.
    • GetObject<T>(string key): Retrieves and deserializes an object into type T.
    IDistributedCache cache = xxxx;
    
    object obj1 = new xxxx();
    cache.SetObject("key1", obj1);
    
    object obj2 = cache.GetObject("key1");
    T obj3 = cache.GetObject<T>("key1");
  9. Configure a Single Machine Redis connection

    master

    Initialize a CSRedisClient using a connection string. The client supports various parameters including password, database selection, and key prefixes.

    Connection String Parameters:

    • user: Redis server user (requires Redis 6.0+)
    • password: Redis server password
    • defaultDatabase: Redis server database (default: 0)
    • asyncPipeline: If true, asynchronous methods automatically use pipeline (improves performance for high concurrency)
    • poolsize: Connection pool size (default: 50)
    • idleTimeout: Idle time for elements in the connection pool in MS
    • connectTimeout: Connection timeout in MS
    • syncTimeout: Send/receive timeout in MS
    • preheat: Number of connections to preheat (default: 5)
    • autoDispose: Automatically release connections on system exit (default: true)
    • ssl: Enable encrypted transmission (default: false)
    • testcluster: Attempt cluster mode (set to false for Alibaba Cloud or Tencent Cloud clusters)
    • tryit: Number of retry attempts on execution error
    • name: Connection name (viewable via CLIENT LIST)
    • prefix: A key prefix applied to all methods. For example, if prefix=my_, calling csredis.Set("key", 111) results in the key my_key in Redis.
    var csredis = new CSRedis.CSRedisClient("127.0.0.1:6379,password=123,defaultDatabase=13,prefix=my_");