SkillAgentSearch skills...

CachingFramework.Redis

Distributed caching based on StackExchange.Redis and Redis. Includes support for tagging and is cluster-compatible.

Install / Use

/learn @thepirat000/CachingFramework.Redis

README

CachingFramework.Redis

issues-open issues-closed

Quality Gate Status Coverage

.NET Redis client library based on StackExchange.Redis adding some interesting features like an extensible serialization strategy, a tagging mechanism to group keys, hash fields and set members, and a fetching mechanism to support atomic add/get operations, all being cluster-compatible.

Features

Usage

NuGet

To install the package run the following command on the Package Manager Console:

PM> Install-Package CachingFramework.Redis

Context

The RedisContext class provides all the functionality divided into five categories, each of which is exposed as a property with the following names:

  • Cache
  • Collections
  • GeoSpatial
  • PubSub
  • KeyEvents

Default configuration

Connect to Redis on localhost port 6379:

var context = new RedisContext();

Custom connection configuration

var context = new RedisContext("10.0.0.1:7000, 10.0.0.2:7000, connectRetry=10, abortConnect=false, allowAdmin=true");

The constructor parameter must be a valid StackExchange.Redis connection string. Check this for more information about StackExchange.Redis configuration options.

Custom database options

var context = new RedisContext("localhost:6379", new DatabaseOptions 
{ 
  KeyPrefix = "Cache:", 
  DbIndex = 2 
});

The DatabaseOptions parameter allows configuring a global Key prefix and Database index to use within the context

Custom multiplexer

You can inject your own multiplexer by using the appropiate constructor overload:

public class PooledConnectionMultiplexer : IConnectionMultiplexer
{
    // ...
}

var myMultiplexer = new PooledConnectionMultiplexer(Common.Config);
var context = new RedisContext(myMultiplexer);

IMPORTANT NOTE:

The RedisContext object should be shared and reused between callers. It is not recommended to create a RedisContext per operation. Please check StackExchange.Redis documentation for more information.

Serialization

Different serialization mechanisms are provided:

| Serializer | Data | Configuration | | ----------- | ----------------------- | -------------------------- | |BinarySerializer | All types are serialized using the .NET BinaryFormatter and GZIP compressed. | Default for .Net Framework | |JsonSerializer | Data is stored as Json using System.Text.Json. Serialization can be configured with JsonSerializerOptions. | Default for .Net Core | |RawSerializer | The simple types are serialized as UTF-8 strings. Any other type is serialized using the default serializer. | Serialization can be set-up per type using SetSerializerFor() | |NewtonsoftJsonSerializer | Data is stored as Json using Newtonsoft.Json. Serialization can be configured with JsonSerializerSettings. | NuGet Package CachingFramework.Redis.NewtonsoftJson | |MsgPackSerializer | Data is stored as MessagePack via MsgPack.Cli. | NuGet Package CachingFramework.Redis.MsgPack | |MemoryPackSerializer | Data is stored using MemoryPack. | NuGet Package CachingFramework.Redis.MemoryPack |

The RedisContext class has constructor overloads to supply the serialization mechanism, for example:

var context = new RedisContext("localhost:6379", new JsonSerializer());

Default serialization method

You can change the default serialization mechanism by setting the static property RedisContext.DefaultSerializer. This default is used when creating RedisContext without an explicit serializer.

Of course you must do this before any context creation, for example on your application startup:

RedisContext.DefaultSerializer = new JsonSerializer();

NOTE: If you don't explicitly set the serializer, it will default depending on the framework: .NET Framework version will default to BinarySerializer and .NET Core to JsonSerializer.

If you plan to consume data from different framework versions, make sure all of them are using the same serialization method.

Custom serialization

To provide a custom serialization mechanism, implement the ISerializer interface (or inherit from SerializerBase class).

For example:

public class MySerializer : SerializerBase
{
    public override RedisValue Serialize<T>(T value)
    {
        return value.ToString();
    }
    public override T Deserialize<T>(RedisValue value)
    {
        return (T)Convert.ChangeType(value.ToString(), typeof(T));
    }
}

Raw serializer

The RawSerializer allows to dynamically override the serialization/deserialization logic per type with the method SetSerializerFor<T>().

For example, to allow the serialization of a StringBuilder as an UTF-8 encoded string:

// On your startup logic:
RedisContext.DefaultSerializer = new RawSerializer()
    .SetSerializerFor<StringBuilder>
    (
        sb => Encoding.UTF8.GetBytes(sb.ToString()), 
        b => new StringBuilder(Encoding.UTF8.GetString(b))
    );

Typed cache

Any primitive type or serializable class can be used as a cache value.

For example:

[Serializable]
public class User
{
    public int Id { get; set; }
    public string UserName { get; set; } ...
}

Note: The Serializable attribute is needed by the default serialization method binary serializer. If you use, for example, the json serializer, this attribute becomes unnecessary. See Serialization section for more information.

Add a single object to the cache:

string redisKey = "user:1";
User value = new User() { Id = 1 };  // any serializable object 
context.Cache.SetObject(redisKey, value);

Add a single object with TTL

Add a single object to the cache with a Time-To-Live of 1 day:

context.Cache.SetObject(redisKey, value, TimeSpan.FromDays(1));

Get a single object

User user = context.Cache.GetObject<User>(redisKey);

Remove a key

context.Cache.Remove(redisKey);

Fetching mechanism

Shortcut methods are provided for atomic

View on GitHub
GitHub Stars299
CategoryCustomer
Updated5d ago
Forks53

Languages

C#

Security Score

85/100

Audited on Mar 22, 2026

No findings