FreeRedis Documentation

repository·master·Indexed 21 days ago

https://github.com/2881099/freeredis

A high-performance .NET Redis client supporting .NET Core, .NET Framework, Xamarin, and AOT. It features support for Cluster, Sentinel, Master-Slave read/write splitting, Pub-Sub, Lua Scripting, Pipelines, Transactions, RediSearch via FtDocumentRepository, and client-side caching for Redis 6.0+.

Tokens
8.8K
Snippets
34
Records
39
Agent score
75%

What's inside FreeRedis

  1. Configure Master-Slave (Read/Write Splitting)

    master

    To implement read/write splitting, provide multiple connection strings to the RedisClient constructor. Writes will be directed to the first address (Master), while reads will be distributed randomly among the subsequent addresses (Slaves).

    public static RedisClient cli = new RedisClient(
        "127.0.0.1:6379,password=123,defaultDatabase=13",
        "127.0.0.1:6380,password=123,defaultDatabase=13",
        "127.0.0.1:6381,password=123,defaultDatabase=13"
        );
    
    var value = cli.Get("key1"); // Reads from 6380 or 6381
  2. Use Client-side Caching

    master

    Requires Redis 6.0+. Use UseClientSideCaching with ClientSideCachingOptions to enable local caching of keys. You can define a KeyFilter to specify which keys are eligible for caching and a CheckExpired function to manage cache expiration logic.

    cli.UseClientSideCaching(new ClientSideCachingOptions
    {
        // Client cache capacity
        Capacity = 3,
        // Filtering rules: specify which keys can be cached locally
        KeyFilter = key => key.StartsWith("Interceptor"),
        // Check long-term unused cache
        CheckExpired = (key, dt) => DateTime.Now.Subtract(dt) > TimeSpan.FromSeconds(2)
    });
  3. Use DelayQueue for Delayed Tasks

    master

    The DelayQueue allows you to enqueue tasks to be executed after a specific delay or at a specific time. You can consume tasks asynchronously using DequeueAsync.

    var delayQueue = cli.DelayQueue("TestDelayQueue");
    
    // Enqueue with relative delay
    delayQueue.Enqueue("Execute in 5 seconds.", TimeSpan.FromSeconds(5));
    
    // Enqueue with absolute time
    delayQueue.Enqueue("Specific time task", DateTime.Parse("2024-07-02 14:30:15"));
    
    // Consume tasks
    await delayQueue.DequeueAsync(async s =>
    {
        Console.WriteLine($"{DateTime.Now}:{s}");
        await Task.CompletedTask;
    });
  4. Quick Start with FreeRedis

    master

    To get started with FreeRedis, instantiate a RedisClient using a connection string. The connection string supports parameters like password and defaultDatabase. You can also subscribe to the Notice event to log command execution. FreeRedis supports various data types including STRING, HASH, LIST, SET, ZSET, BITMAP, HyperLogLog, GEO, Stream, and Bloom Filters.

    public static RedisClient cli = new RedisClient("127.0.0.1:6379,password=123,defaultDatabase=13");
    // Optional: Custom serialization/deserialization
    // cli.Serialize = obj => JsonConvert.SerializeObject(obj);
    // cli.Deserialize = (json, type) => JsonConvert.DeserializeObject(json, type);
    
    cli.Notice += (s, e) => Console.WriteLine(e.Log); // Print command logs
    
    cli.Set("key1", "value1");
    cli.MSet("key1", "value1", "key2", "value2");
    
    string value1 = cli.Get("key1");
    string[] vals = cli.MGet("key1", "key2");
  5. Use RediSearch with FtDocumentRepository

    master

    FreeRedis provides a high-level repository pattern for RediSearch. You can define your schema using attributes on a class and use FtDocumentRepository<T> to perform CRUD and complex searches.

    [FtDocument("index_post", Prefix = "blog:post:")]
    class TestDoc
    {
        [FtKey]
        public int Id { get; set; }
    
        [FtTextField("title", Weight = 5.0)]
        public string Title { get; set; }
    
        [FtTagField("tags")]
        public string[] Tags { get; set; }
    
        [FtNumericField("views")]
        public int Views { get; set; }
    }
    
    // Usage
    var repo = cli.FtDocumentRepository<TestDoc>();
    repo.CreateIndex();
    
    // Save and Search
    repo.Save(new TestDoc { Id = 1, Title = "test title", Tags = new[]{"user1"}, Views = 101 });
    var list = repo.Search("word").ToList();
    var filtered = repo.Search(a => a.Title == "word" && a.Tags.Contains("user1"))
                      .Filter(a => a.Views, 1, 1000)
                      .ToList();
  6. Connect to Redis Sentinel

    master

    To connect via Redis Sentinel, provide the master name and password as the first argument, followed by an array of Sentinel node addresses. Set the boolean flag to true to enable read-write separation mode.

    public static RedisClient cli = new RedisClient(
        "mymaster,password=123", 
        new [] { "192.169.1.10:26379", "192.169.1.11:26379", "192.169.1.12:26379" },
        true // Enables read-write separation mode
        );
  7. Enable Client-side Caching

    master

    Requires Redis server 6.0 or higher. Use UseClientSideCaching with ClientSideCachingOptions to manage local cache capacity, key filtering, and expiration checks.

    cli.UseClientSideCaching(new ClientSideCachingOptions
    {
        // Local cache capacity
        Capacity = 3,
        // Filter which keys are cached
        KeyFilter = key => key.StartsWith("Interceptor"),
        // Check for long-unused cache
        CheckExpired = (key, dt) => DateTime.Now.Subtract(dt) > TimeSpan.FromSeconds(2)
    });
  8. Configure Redis Sentinel for High Availability

    master

    To use Redis Sentinel, provide the master name and the list of Sentinel nodes. You can also enable read/write splitting by passing true as the third argument.

    public static RedisClient cli = new RedisClient(
        "mymaster,password=123", 
        new [] { "192.169.1.10:26379", "192.169.1.11:26379", "192.169.1.12:26379" },
        true // Enable read/write splitting
        );
  9. Connect to Redis Cluster

    master

    For Redis Cluster support (requires redis-server 3.2+), pass an array of ConnectionStringBuilder objects containing the addresses of the cluster nodes.

    public static RedisClient cli = new RedisClient(
        new ConnectionStringBuilder[] { "192.168.0.2:7001", "192.168.0.2:7002", "192.168.0.2:7003" }
        );
  10. Subscribe to Redis Pub-Sub, Streams, and Lists

    master

    FreeRedis provides specialized subscription methods for different Redis data types. These methods return an IDisposable object; you must wait for .Dispose() to stop listening.

    • Pub-Sub: Use Subscribe(channel, callback).
    • Streams: Use SubscribeStream(streamKey, callback) for xadd + xreadgroup patterns.
    • Lists: Use SubscribeList(listKey, callback) for lpush + blpop patterns.
    // Pub-Sub
    using (cli.Subscribe("abc", (channel, data) => Console.WriteLine($"{channel} -> {data}")))
    {
        Console.ReadKey();
    }
    
    // Streams
    using (cli.SubscribeStream("stream_key", (streamValue) => Console.WriteLine(JsonConvert.SerializeObject(streamValue))))
    {
        Console.ReadKey();
    }
    
    // Lists
    using (cli.SubscribeList("list_key", (listValue) => Console.WriteLine(listValue)))
    {
        Console.ReadKey();
    }
  11. Connect to Redis Master-Slave setup

    master

    To use a Master-Slave configuration, pass the master node address as the first argument and subsequent slave node addresses as additional arguments. Writes are directed to the master, while reads are distributed among the slaves.

    public static RedisClient cli = new RedisClient(
        "127.0.0.1:6379,password=123,defaultDatabase=13",
        "127.0.0.1:6380,password=123,defaultDatabase=13",
        "127.0.0.1:6381,password=123,defaultDatabase=13"
        );
    
    var value = cli.Get("key1");
  12. Use Transactions with Multi/Exec

    master

    Transactions ensure that a block of commands are executed atomically. Use Multi() to start a transaction and Exec() to commit it.

    using (var tran = cli.Multi())
    {
        tran.IncrBy("key1", 10);
        tran.Set("key2", Null);
        tran.Get("key1");
    
        object[] ret = tran.Exec();
        Console.WriteLine(ret[0] + ", " + ret[2]);
    }