redis

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Redis Skill

Redis 技能模块

Sorcha uses Redis via StackExchange.Redis for caching, token revocation tracking, rate limiting, and distributed coordination. All services share a single Redis instance managed by .NET Aspire with circuit breaker resilience.
Sorcha 通过 StackExchange.Redis 利用 Redis 实现缓存、令牌吊销跟踪、速率限制和分布式协调。所有服务共享一个由 .NET Aspire 管理的 Redis 实例,并配备断路器容错机制。

Quick Start

快速开始

Aspire Configuration

Aspire 配置

csharp
// src/Apps/Sorcha.AppHost/AppHost.cs
var redis = builder.AddRedis("redis")
    .WithRedisCommander();

// Reference from any service
var blueprintService = builder.AddProject<Projects.Sorcha_Blueprint_Service>()
    .WithReference(redis);
csharp
// src/Apps/Sorcha.AppHost/AppHost.cs
var redis = builder.AddRedis("redis")
    .WithRedisCommander();

// Reference from any service
var blueprintService = builder.AddProject<Projects.Sorcha_Blueprint_Service>()
    .WithReference(redis);

Cache Store Usage

缓存存储使用

csharp
// Inject ICacheStore from Sorcha.Storage.Redis
public class MyService(ICacheStore cache)
{
    public async Task<User?> GetUserAsync(string id)
    {
        return await cache.GetAsync<User>($"user:{id}");
    }
    
    public async Task SetUserAsync(User user)
    {
        await cache.SetAsync($"user:{user.Id}", user, TimeSpan.FromMinutes(15));
    }
}
csharp
// Inject ICacheStore from Sorcha.Storage.Redis
public class MyService(ICacheStore cache)
{
    public async Task<User?> GetUserAsync(string id)
    {
        return await cache.GetAsync<User>($"user:{id}");
    }
    
    public async Task SetUserAsync(User user)
    {
        await cache.SetAsync($"user:{user.Id}", user, TimeSpan.FromMinutes(15));
    }
}

Direct IConnectionMultiplexer

直接使用 IConnectionMultiplexer

csharp
// For operations beyond ICacheStore (Sets, rate limiting, etc.)
public class TokenService(IConnectionMultiplexer redis)
{
    private readonly IDatabase _db = redis.GetDatabase();
    
    public async Task TrackTokenAsync(string userId, string jti)
    {
        await _db.SetAddAsync($"auth:user_tokens:{userId}", jti);
    }
}
csharp
// For operations beyond ICacheStore (Sets, rate limiting, etc.)
public class TokenService(IConnectionMultiplexer redis)
{
    private readonly IDatabase _db = redis.GetDatabase();
    
    public async Task TrackTokenAsync(string userId, string jti)
    {
        await _db.SetAddAsync($"auth:user_tokens:{userId}", jti);
    }
}

Key Concepts

核心概念

ConceptUsageExample
Key prefixNamespace isolation
sorcha:
,
auth:
TTLAutomatic expiration
TimeSpan.FromMinutes(15)
Circuit breakerGraceful degradationBreaks after 5 failures
SetsToken tracking
SetAddAsync
,
SetMembersAsync
CountersRate limiting
StringIncrementAsync
概念用途示例
键前缀命名空间隔离
sorcha:
,
auth:
TTL自动过期
TimeSpan.FromMinutes(15)
断路器优雅降级5次失败后触发断路
集合令牌跟踪
SetAddAsync
,
SetMembersAsync
计数器速率限制
StringIncrementAsync

Common Patterns

常见模式

Rate Limiting

速率限制

When: Protecting auth endpoints from brute force.
csharp
public async Task<bool> IsRateLimitedAsync(string identifier)
{
    var key = $"auth:failed:{identifier}";
    var count = await _db.StringIncrementAsync(key);
    
    if (count == 1)
        await _db.KeyExpireAsync(key, TimeSpan.FromSeconds(60));
    
    return count >= MaxFailedAttempts;
}
适用场景: 保护认证端点免受暴力攻击。
csharp
public async Task<bool> IsRateLimitedAsync(string identifier)
{
    var key = $"auth:failed:{identifier}";
    var count = await _db.StringIncrementAsync(key);
    
    if (count == 1)
        await _db.KeyExpireAsync(key, TimeSpan.FromSeconds(60));
    
    return count >= MaxFailedAttempts;
}

Token Revocation

令牌吊销

When: Invalidating JWTs before expiration.
csharp
public async Task RevokeTokenAsync(string jti, DateTimeOffset expiresAt)
{
    var ttl = expiresAt - DateTimeOffset.UtcNow;
    if (ttl > TimeSpan.Zero)
        await _db.StringSetAsync($"auth:revoked:{jti}", "revoked", ttl);
}
适用场景: 在令牌过期前使其失效。
csharp
public async Task RevokeTokenAsync(string jti, DateTimeOffset expiresAt)
{
    var ttl = expiresAt - DateTimeOffset.UtcNow;
    if (ttl > TimeSpan.Zero)
        await _db.StringSetAsync($"auth:revoked:{jti}", "revoked", ttl);
}

See Also

相关链接

  • patterns - Caching, resilience, key naming
  • workflows - Setup, testing, debugging
  • patterns - 缓存、容错、键命名规范
  • workflows - 安装、测试、调试流程

Related Skills

相关技能组件

  • aspire - Redis resource configuration and service discovery
  • jwt - Token revocation integration
  • signalr - Redis backplane for scale-out
  • docker - Redis container configuration
  • aspire - Redis资源配置与服务发现
  • jwt - 令牌吊销集成
  • signalr - 用于横向扩展的Redis背板
  • docker - Redis容器配置

Documentation Resources

文档资源

Fetch latest Redis and StackExchange.Redis documentation with Context7.
How to use Context7:
  1. Use
    mcp__context7__resolve-library-id
    to search for "StackExchange.Redis" or "redis"
  2. Prefer website documentation (
    /websites/redis_io
    ) for concepts
  3. Use
    /stackexchange/stackexchange.redis
    for .NET-specific patterns
Library IDs:
  • /stackexchange/stackexchange.redis
    - .NET client (344 snippets)
  • /websites/redis_io
    - Redis concepts (29k+ snippets)
Recommended Queries:
  • "Connection pooling multiplexer patterns best practices"
  • "Caching patterns TTL expiration strategies"
  • "Pub/Sub patterns distributed systems"
使用Context7获取最新的Redis和StackExchange.Redis文档。
如何使用Context7:
  1. 使用
    mcp__context7__resolve-library-id
    搜索 "StackExchange.Redis" 或 "redis"
  2. 优先选择官网文档 (
    /websites/redis_io
    ) 了解概念
  3. 使用
    /stackexchange/stackexchange.redis
    获取.NET特定模式
库ID:
  • /stackexchange/stackexchange.redis
    - .NET客户端(344个代码片段)
  • /websites/redis_io
    - Redis概念(29000+个代码片段)
推荐查询:
  • "Connection pooling multiplexer patterns best practices"(连接池多路复用器模式最佳实践)
  • "Caching patterns TTL expiration strategies"(缓存模式TTL过期策略)
  • "Pub/Sub patterns distributed systems"(发布/订阅模式分布式系统)