StackExchange.Redis.Extensions 是一个扩展了 StackExchange.Redis 的库,使得在 .NET 应用程序中使用 Redis 更加方便。
StackExchange.Redis.Extensions 是一个扩展了 StackExchange.Redis 的库,使得在 .NET 应用程序中使用 Redis 更加方便。
StackExchange.Redis.Extensions is a library that extends StackExchange.Redis, making it easier to work with Redis in .NET applications. It wraps the base library with serialization, connection pooling, and higher-level APIs so you can store and retrieve complex objects without writing boilerplate code.
AI-Ready: This library provides an
llms.txtfile for AI coding assistants and a Claude Code plugin for configuration, scaffolding, and troubleshooting.claude plugin add imperugo/StackExchange.Redis.ExtensionsThen use
/redis-configure,/redis-scaffold, or/redis-diagnosein Claude Code.
IDistributedCache adapter (Microsoft-compatible Hash schema)[FromKeyedServices] supportgraph TB
App[Your Application] --> DI[ASP.NET Core DI]
DI --> Factory[IRedisClientFactory]
Factory --> Client1[IRedisClient - Default]
Factory --> Client2[IRedisClient - Named]
Client1 --> DB[IRedisDatabase]
DB --> Pool[Connection Pool Manager]
Pool --> C1[Connection 1]
Pool --> C2[Connection 2]
Pool --> C3[Connection N...]
DB --> Ser[ISerializer]
Ser --> Comp[CompressedSerializer?]
Comp --> Inner[System.Text.Json / Newtonsoft / ...]
C1 --> Redis[(Redis Server)]
C2 --> Redis
C3 --> Redisdotnet add package StackExchange.Redis.Extensions.Core
dotnet add package StackExchange.Redis.Extensions.System.Text.Json
dotnet add package StackExchange.Redis.Extensions.AspNetCoreappsettings.json{
"Redis": {
"Password": "",
"AllowAdmin": true,
"Ssl": false,
"ConnectTimeout": 5000,
"SyncTimeout": 5000,
"Database": 0,
"Hosts": [
{ "Host": "localhost", "Port": 6379 }
],
"PoolSize": 5,
"IsDefault": true
}
}var redisConfig = builder.Configuration.GetSection("Redis").Get();
builder.Services.AddStackExchangeRedisExtensions(redisConfig);…| Package | Description | NuGet |
|---|---|---|
| Core | Core library with abstractions and implementations | |
| AspNetCore | ASP.NET Core DI integration and middleware |
// Set a hash field
await redis.HashSetAsync("user:1", "name", "Ugo");
await redis.HashSetAsync("user:1", "email", "[email protected]");
// Get a hash field
var name = await redis.HashGetAsync("user:1", "name");
// Set with per-field expiry (Redis 7.4+)
await redis.HashSetWithExpiryAsync("user:1", "session", sessionData, TimeSpan.FromMinutes(30));
// Query field TTL
var ttl = await redis.HashFieldGetTimeToLiveAsync("user:1", new[] { "session" });…// Publish typed events
await redis.StreamAddAsync("orders", "payload", new Order { Id = 1, Total = 99.99m });
// Consumer group workflow
await redis.StreamCreateConsumerGroupAsync("orders", "processors");
var entries = await redis.StreamReadGroupAsync("orders", "processors", "worker-1");
foreach (var entry in entries)
{
// Process the message
await redis.StreamAcknowledgeAsync("orders", "processors", entry.Id!);
}// Subscribe to typed messages
await redis.SubscribeAsync("orders:new", async order =>
{
Console.WriteLine($"New order: {order.Id}");
});
// Publish
await redis.PublishAsync("orders:new", new OrderEvent { Id = 42 });// Increment/decrement with long (default step = 1)
var views = await redis.StringIncrementAsync("page:views");
var stock = await redis.StringDecrementAsync("product:123:stock");
// Custom step
await redis.StringIncrementAsync("stats:bytes", 1024);
// Double precision
await redis.StringIncrementAsync("account:balance", 49.99);// Combine sets: union, intersect, difference
var allTags = await redis.SetCombineAsync(SetOperation.Union, "user:1:tags", "user:2:tags");
var commonTags = await redis.SetCombineAsync(SetOperation.Intersect, "user:1:tags", "user:2:tags");
// Store result in a new key
await redis.SetCombineAndStoreAsync(SetOperation.Union, "all:tags", new[] { "set:a", "set:b", "set:c" });// Count unique visitors
await redis.HyperLogLogAddAsync("page:home:visitors", userId);
var uniqueCount = await redis.HyperLogLogLengthAsync("page:home:visitors");
// Merge daily counts into a monthly aggregate
await redis.HyperLogLogMergeAsync("visitors:2024:01", new[]
{
"visitors:2024:01:01",
"visitors:2024:01:02",
"visitors:2024:01:03",
});// Acquire a lock with automatic release on dispose
await using var lockObj = await redis.LockAcquireAsync(
"resource:order:123",
expiry: TimeSpan.FromSeconds(30),
maxRetries: 5,
retryDelay: TimeSpan.FromMilliseconds(200));
if (lockObj is not null)
{
// Critical section — lock is held
await ProcessOrder(123);
}
// Lock released automatically on dispose// Track daily active users (1 bit per user ID)
await redis.StringSetBitAsync("dau:2024-01-15", userId, true);
// Count active users
var activeCount = await redis.StringBitCountAsync("dau:2024-01-15");
// Compute users active on ALL days (AND operation)
await redis.StringBitOperationAsync(Bitwise.And, "wau:all-days", new[]
{
"dau:2024-01-15", "dau:2024-01-16", "dau:2024-01-17",
});…Note: Uses a Hash-based schema (
data/absexp/sldexp) compatible withMicrosoft.Extensions.Caching.StackExchangeRedis, enabling zero-downtime migration between providers.
// Register the health check
builder.Services.AddHealthChecks()
.AddRedisExtensionsHealthCheck();
// Returns:
// - Healthy: all pool connections active + PING OK
// - Degraded: some connections invalid but Redis responding
// - Unhealthy: all connections invalid or PING fails// Register with named configurations
builder.Services.AddStackExchangeRedisExtensions(new[]
{
new RedisConfiguration { Name = "cache", IsDefault = true, /* ... */ },
new RedisConfiguration { Name = "session", /* ... */ },
});
// Inject by name using [FromKeyedServices]
public class MyService(
[FromKeyedServices("cache")] IRedisDatabase cacheDb,
[FromKeyedServices("session")] IRedisDatabase sessionDb)
{
// Each resolves to its own Redis instance with isolated connection pool
}// Enable transparent compression with any serializer
services.AddStackExchangeRedisExtensions(config);
services.AddRedisCompression(); // That's it!
// All operations automatically compress/decompress
await redis.AddAsync("large-data", myLargeObject); // stored compressed
var obj = await redis.GetAsync("large-data"); // decompressed automaticallyvar config = new RedisConfiguration { /* ... */ };
config.ConfigurationOptionsAsyncHandler = async opts =>
{
await opts.ConfigureForAzureWithTokenCredentialAsync(new DefaultAzureCredential());
return opts;
};graph LR
subgraph Pool["Connection Pool (PoolSize=5)"]
C1["Connection 1
Outstanding: 3"]
C2["Connection 2
Outstanding: 0"]
C3["Connection 3
Outstanding: 7"]
C4["Connection 4
Outstanding: 1"]
C5["Connection 5
Outstanding: 2"]
end
Op["GetConnection()"] -->|LeastLoaded| C2
Op -->|RoundRobin| C4
style C2 fill:#90EE90
style C4 fill:#87CEEBThe pool automatically skips disconnected connections and falls back gracefully when all connections are down, letting StackExchange.Redis's internal reconnection logic recover.
| Strategy | Behavior |
|---|---|
LeastLoaded (default) |
Picks the connected connection with fewest outstanding commands |
RoundRobin |
Random selection among connected connections |
All values stored in Redis go through the configured ISerializer. This means:
string value "hello" is stored as "\"hello\"" (JSON-encoded)IRedisDatabase.Database for raw Redis operations without serializationnull input produces an empty byte array| Property | Default | Description |
|---|---|---|
Hosts |
Required | Redis server endpoints |
Password |
null |
Redis password |
Database |
0 |
Database index |
Ssl |
false |
Enable TLS |
PoolSize |
5 |
Number of connections in the pool |
ConnectionSelectionStrategy |
LeastLoaded |
Pool selection strategy |
SyncTimeout |
5000 |
Sync operation timeout (ms) |
| `ConnectTi |
暂无开放 Issues,或尚未同步最近议题。