百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
S

StackExchange.Redis.Extensions

> 数据库
开源

StackExchange.Redis.Extensions 是一个扩展了 StackExchange.Redis 的库,使得在 .NET 应用程序中使用 Redis 更加方便。

625 stars0 点赞2 次浏览
访问官网GitHub

工具介绍

StackExchange.Redis.Extensions 是一个扩展了 StackExchange.Redis 的库,使得在 .NET 应用程序中使用 Redis 更加方便。

StackExchange.Redis.Extensions

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.txt file for AI coding assistants and a Claude Code plugin for configuration, scaffolding, and troubleshooting.

bash
claude plugin add imperugo/StackExchange.Redis.Extensions

Then use /redis-configure, /redis-scaffold, or /redis-diagnose in Claude Code.

Features

  • Store and retrieve complex .NET objects with automatic serialization
  • Multiple serialization providers (System.Text.Json, Newtonsoft, Protobuf, MsgPack, MemoryPack, and more)
  • Connection pooling with LeastLoaded and RoundRobin strategies
  • Pub/Sub messaging with typed handlers
  • Hash operations with per-field expiry (Redis 7.4+)
  • GeoSpatial indexes (GEOADD, GEOSEARCH, GEODIST, etc.)
  • Redis Streams with consumer group support
  • Set, List, and Sorted Set operations with Set Combine (union, intersect, diff)
  • HyperLogLog for probabilistic cardinality estimation
  • Distributed locking with IAsyncDisposable auto-release
  • Bitmap operations for analytics and feature flags
  • Lua scripting for atomic server-side operations
  • Key tagging and search
  • Key management (rename, type, dump/restore)
  • Atomic counters (StringIncrement/StringDecrement)
  • Transparent compression (GZip, Brotli, LZ4, Snappy, Zstandard)
  • IDistributedCache adapter (Microsoft-compatible Hash schema)
  • ASP.NET Core Health Check for connection pool monitoring
  • Azure Managed Identity support
  • ASP.NET Core integration with DI and .NET 8+ Keyed Services
  • Multiple named Redis instances with [FromKeyedServices] support
  • OpenTelemetry integration
  • .NET Standard 2.1, .NET 8, .NET 9, .NET 10

Architecture

mermaid
graph 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 --> Redis

Quick Start

1. Install packages

bash
dotnet add package StackExchange.Redis.Extensions.Core
dotnet add package StackExchange.Redis.Extensions.System.Text.Json
dotnet add package StackExchange.Redis.Extensions.AspNetCore

2. Configure in appsettings.json

json
{
  "Redis": {
    "Password": "",
    "AllowAdmin": true,
    "Ssl": false,
    "ConnectTimeout": 5000,
    "SyncTimeout": 5000,
    "Database": 0,
    "Hosts": [
      { "Host": "localhost", "Port": 6379 }
    ],
    "PoolSize": 5,
    "IsDefault": true
  }
}

3. Register in DI

csharp
var redisConfig = builder.Configuration.GetSection("Redis").Get();
builder.Services.AddStackExchangeRedisExtensions(redisConfig);

4. Use it

…

NuGet Packages

Core

Package Description NuGet
Core Core library with abstractions and implementations
AspNetCore ASP.NET Core DI integration and middleware

Serializers (pick one)

Package Description NuGet
System.Text.Json Recommended for most scenarios
Newtonsoft JSON.NET for legacy compatibility
MemoryPack High-performance binary (net7.0+)
MsgPack MessagePack binary format
Protobuf Protocol Buffers
Utf8Json UTF-8 native JSON

Compressors (optional)

Package Algorithm Best for NuGet
Compression.LZ4 LZ4 Lowest latency
Compression.Snappier Snappy Low latency
Compression.ZstdSharp Zstandard Best ratio/speed
Compression.GZip GZip Wide compatibility
Compression.Brotli Brotli Best ratio for text

Usage Examples

Hash Operations

csharp
// 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" });

GeoSpatial

…

Redis Streams

csharp
// 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!);
}

Pub/Sub

csharp
// 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 });

Atomic Counters

csharp
// 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);

Set Operations

csharp
// 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" });

HyperLogLog

csharp
// 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",
});

Distributed Lock

csharp
// 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

Bitmap Operations

csharp
// 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",
});

Lua Scripting

…

Note: Uses a Hash-based schema (data/absexp/sldexp) compatible with Microsoft.Extensions.Caching.StackExchangeRedis, enabling zero-downtime migration between providers.

Health Check

csharp
// 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

Keyed DI Services (.NET 8+)

csharp
// 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
}

Compression

csharp
// 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 automatically

Azure Managed Identity

csharp
var config = new RedisConfiguration { /* ... */ };
config.ConfigurationOptionsAsyncHandler = async opts =>
{
    await opts.ConfigureForAzureWithTokenCredentialAsync(new DefaultAzureCredential());
    return opts;
};

Connection Pooling

mermaid
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:#87CEEB

The 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

Serialization Behavior

All values stored in Redis go through the configured ISerializer. This means:

  • A string value "hello" is stored as "\"hello\"" (JSON-encoded)
  • Use IRedisDatabase.Database for raw Redis operations without serialization
  • All serializers follow the same convention: null input produces an empty byte array

Configuration Reference

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· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

C#c-sharpcachecachingdotnet

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类数据库
定价开源

> 相关工具

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库