Smart.StackRedis
4.1.1
See the version list below for details.
dotnet add package Smart.StackRedis --version 4.1.1
NuGet\Install-Package Smart.StackRedis -Version 4.1.1
<PackageReference Include="Smart.StackRedis" Version="4.1.1" />
<PackageVersion Include="Smart.StackRedis" Version="4.1.1" />
<PackageReference Include="Smart.StackRedis" />
paket add Smart.StackRedis --version 4.1.1
#r "nuget: Smart.StackRedis, 4.1.1"
#:package Smart.StackRedis@4.1.1
#addin nuget:?package=Smart.StackRedis&version=4.1.1
#tool nuget:?package=Smart.StackRedis&version=4.1.1
Smart.StackRedis
<a name="english"></a>
English
Smart.StackRedis is a modern Redis client library built on top of StackExchange.Redis, designed for .NET 8, 9 and 10 platforms. It provides native dependency injection support, type-safe operations, and follows modern .NET development conventions.
Features
- Native Dependency Injection: Seamless integration with Microsoft.Extensions.DependencyInjection
- Fully Async Operations: Complete async/await support for all operations
- Global Key Prefix: Automatic key prefixing for all operations
- Distributed Lock: Built-in distributed lock support with timeout handling
- Atomic Operations: Redis counter with atomic increment/decrement operations
- Pub/Sub Support: Complete publish/subscribe functionality with automatic re-subscription on connection restore
- Modular Data Types: Separate modules for each Redis data type (String, Hash, List, Set, SortedSet, Stream)
- Connection Management: Automatic reconnection and connection pool management
- JSON Serialization: Integrated JSON serialization with customizable options
- Transaction Support: Redis transactions for multi-operation atomicity
- Pipeline Operations: Batch operations using Redis pipelines for better performance
Installation
Install the package via NuGet:
dotnet add package Smart.StackRedis
Configuration
1. Service Registration
Register the Redis service in your Program.cs or Startup.cs:
using Smart.StackRedis;
builder.Services.AddSmartRedis(new RedisOptions
{
Server = "127.0.0.1:6379,password=password,asyncTimeout=5000,abortConnect=false",
Prefix = "prod:"
});
Or use configuration from appsettings.json:
{
"RedisOptions": {
"Server": "localhost:6379,connectRetry=3",
"Prefix": "prod:",
"ConnectTimeout": 15000,
"SyncTimeout": 5000,
"AbortOnConnectFail": false,
"ConnectRetry": 3
}
}
builder.Services.AddSmartRedis(builder.Configuration.GetSection("RedisOptions"));
Usage Examples
1. Basic String Operations
Store and retrieve objects with automatic JSON serialization:
public class UserService(SmartRedisService redis)
{
public async Task CacheUser(User user)
{
await redis.String.SetAsync($"users:{user.Id}", user, TimeSpan.FromHours(1));
}
public async Task<User?> GetUser(string userId)
{
return await redis.String.GetAsync<User>($"users:{userId}");
}
}
2. Hash Operations
Manage hash fields efficiently:
public class ProfileService(SmartRedisService redis)
{
public async Task UpdateProfile(string userId, string field, object value)
{
await redis.Hash.SetAsync($"profiles:{userId}", field, value);
}
public async Task<Dictionary<string, T?>> GetProfile<T>(string userId)
{
return await redis.Hash.GetAllAsync<T>($"profiles:{userId}");
}
}
3. List Operations
Implement queues and stacks:
public class QueueService(SmartRedisService redis)
{
public async Task EnqueueJob(Job job)
{
await redis.List.RightPushAsync("jobs:queue", job);
}
public async Task<Job?> DequeueJob()
{
return await redis.List.LeftPopAsync<Job>("jobs:queue");
}
}
4. Set Operations
Manage unique collections:
public class TagService(SmartRedisService redis)
{
public async Task AddTags(string userId, params string[] tags)
{
await redis.Set.AddAsync($"user:{userId}:tags", tags);
}
public async Task<string[]> GetTags(string userId)
{
return await redis.Set.MembersAsync($"user:{userId}:tags");
}
}
5. Sorted Set Operations
Handle ranked data:
public class LeaderboardService(SmartRedisService redis)
{
public async Task AddScore(string userId, double score)
{
await redis.SortedSet.AddAsync("leaderboard", userId, score);
}
public async Task<Dictionary<string, double>> GetTopPlayers(int count)
{
return await redis.SortedSet.RangeByRankAsync("leaderboard", 0, count - 1, Order.Descending);
}
}
6. Stream Operations
Process message streams:
public class EventService(SmartRedisService redis)
{
public async Task PublishEvent(string eventType, Dictionary<string, string> data)
{
await redis.Stream.AddAsync($"events:{eventType}", data);
}
public async Task<StreamEntry[]> ReadEvents(string eventType, string groupName, string consumerName)
{
return await redis.Stream.ReadGroupAsync($"events:{eventType}", groupName, consumerName);
}
}
7. Distributed Lock
Implement distributed locking:
public class OrderService(SmartRedisService redis)
{
public async Task ProcessOrder(string orderId)
{
var lockKey = $"order:lock:{orderId}";
var acquired = await redis.Lock.AcquireAsync(lockKey, TimeSpan.FromSeconds(30));
if (!acquired)
{
throw new InvalidOperationException("Order is being processed by another instance");
}
try
{
await ProcessOrderInternal(orderId);
}
finally
{
await redis.Lock.ReleaseAsync(lockKey);
}
}
}
8. Atomic Counter
Implement distributed counters:
public class CounterService(SmartRedisService redis)
{
public async Task<long> IncrementViewCount(string articleId)
{
return await redis.Counter.IncrementAsync($"article:{articleId}:views");
}
public async Task<long> GetViewCount(string articleId)
{
return await redis.Counter.GetAsync($"article:{articleId}:views");
}
}
9. Publish/Subscribe
Implement pub/sub messaging:
public class NotificationService(SmartRedisService redis)
{
public NotificationService(SmartRedisService redis)
{
redis.SubscribeReceived += OnMessageReceived;
}
private void OnMessageReceived(string channel, string message)
{
Console.WriteLine($"Received message on {channel}: {message}");
}
public async Task SubscribeToNotifications()
{
await redis.Subscribe.SubscribeAsync("notifications");
}
public async Task PublishNotification(string message)
{
await redis.Subscribe.PublishAsync("notifications", message);
}
}
10. Pipeline Operations
Batch operations for better performance:
public class BatchService(SmartRedisService redis)
{
public async Task BatchUpdate(Dictionary<string, string> data)
{
var batch = redis.GetDatabase().CreateBatch();
var tasks = data.Select(kv =>
batch.StringSetAsync(kv.Key, kv.Value)
).ToArray();
batch.Execute();
await Task.WhenAll(tasks);
}
}
Core Modules
| Module | Description | Example Methods |
|---|---|---|
| RedisKey | Key management operations | ExistsAsync, DeleteAsync, ExpireAsync |
| RedisString | String/object storage | SetAsync<T>, GetAsync<T>, SetExpiryAsync |
| RedisHash | Hash field operations | SetAsync, GetAsync<T>, GetAllAsync<T> |
| RedisList | Queue/stack operations | LeftPushAsync, RightPopAsync, RangeAsync |
| RedisSet | Unique collection operations | AddAsync, MembersAsync, RemoveAsync |
| RedisSortedSet | Ranked collection operations | AddAsync, RangeByRankAsync, RangeByScoreAsync |
| RedisStream | Message stream processing | AddAsync, ReadGroupAsync, CreateGroupAsync |
| RedisLock | Distributed lock | AcquireAsync, ReleaseAsync, IsAcquiredAsync |
| RedisCounter | Atomic counter | IncrementAsync, DecrementAsync, GetAsync |
| RedisSubscribe | Publish/subscribe | PublishAsync, SubscribeAsync, UnsubscribeAsync |
Configuration Options
public class RedisOptions
{
public string Server { get; set; }
public string Prefix { get; set; }
public int ConnectTimeout { get; set; } = 15000;
public int SyncTimeout { get; set; } = 5000;
public bool AbortOnConnectFail { get; set; } = false;
public int ConnectRetry { get; set; } = 3;
public JsonSerializerOptions JsonSerializerOptions { get; set; }
}
Best Practices
Key Naming Convention
- Use the format
business:environment:entity:id - Example:
orders:prod:2024,users:dev:session:12345
- Use the format
Batch Operations
- Use pipelines for bulk operations to reduce round trips
- Example: Batch set multiple keys in a single operation
Error Handling
try { await redis.String.SetAsync(...); } catch (RedisConnectionException ex) { // Handle connection errors } catch (RedisTimeoutException ex) { // Handle timeout errors }Connection String
- Always include
abortConnect=falseto allow reconnection - Set appropriate timeout values based on your network conditions
- Always include
Memory Management
- Set appropriate expiration times for cached data
- Use
ExpireAsyncto set TTL on keys
Important Notes
- Connection String: Must include
abortConnect=falsefor automatic reconnection - Security: Store sensitive configuration (passwords) in secure configuration providers
- Performance: Avoid creating connections frequently in hot paths
- Pub/Sub: Handle message backlog scenarios for pub/sub operations
- Stream: Redis Stream operations require Redis 5.0 or higher
- Thread Safety: The
SmartRedisServiceinstance is thread-safe and can be shared across the application
<a name="chinese"></a>
中文
Smart.StackRedis 是一个基于 StackExchange.Redis 构建的现代化 Redis 客户端库,专为 .NET 8、9 和 10 平台设计。它提供原生依赖注入支持、类型安全的操作,并遵循现代 .NET 开发规范。
功能特性
- 原生依赖注入: 与 Microsoft.Extensions.DependencyInjection 无缝集成
- 全异步操作: 所有操作均支持 async/await
- 全局键前缀: 所有操作自动附加键前缀
- 分布式锁: 内置分布式锁支持,带超时处理
- 原子操作: Redis 计数器支持原子递增/递减操作
- 发布订阅: 完整的发布/订阅功能,连接恢复时自动重新订阅
- 模块化数据类型: 为每种 Redis 数据类型提供独立模块(String、Hash、List、Set、SortedSet、Stream)
- 连接管理: 自动重连和连接池管理
- JSON 序列化: 集成 JSON 序列化,支持自定义选项
- 事务支持: Redis 事务支持多操作原子性
- 管道操作: 使用 Redis 管道进行批量操作以提升性能
安装
通过 NuGet 安装:
dotnet add package Smart.StackRedis
配置
1. 服务注册
在 Program.cs 或 Startup.cs 中注册 Redis 服务:
using Smart.StackRedis;
builder.Services.AddSmartRedis(new RedisOptions
{
Server = "127.0.0.1:6379,password=password,asyncTimeout=5000,abortConnect=false",
Prefix = "prod:"
});
或从 appsettings.json 加载配置:
{
"RedisOptions": {
"Server": "localhost:6379,connectRetry=3",
"Prefix": "prod:",
"ConnectTimeout": 15000,
"SyncTimeout": 5000,
"AbortOnConnectFail": false,
"ConnectRetry": 3
}
}
builder.Services.AddSmartRedis(builder.Configuration.GetSection("RedisOptions"));
使用示例
1. 基础字符串操作
存储和检索对象,自动进行 JSON 序列化:
public class UserService(SmartRedisService redis)
{
public async Task CacheUser(User user)
{
await redis.String.SetAsync($"users:{user.Id}", user, TimeSpan.FromHours(1));
}
public async Task<User?> GetUser(string userId)
{
return await redis.String.GetAsync<User>($"users:{userId}");
}
}
2. 哈希表操作
高效管理哈希字段:
public class ProfileService(SmartRedisService redis)
{
public async Task UpdateProfile(string userId, string field, object value)
{
await redis.Hash.SetAsync($"profiles:{userId}", field, value);
}
public async Task<Dictionary<string, T?>> GetProfile<T>(string userId)
{
return await redis.Hash.GetAllAsync<T>($"profiles:{userId}");
}
}
3. 列表操作
实现队列和栈:
public class QueueService(SmartRedisService redis)
{
public async Task EnqueueJob(Job job)
{
await redis.List.RightPushAsync("jobs:queue", job);
}
public async Task<Job?> DequeueJob()
{
return await redis.List.LeftPopAsync<Job>("jobs:queue");
}
}
4. 集合操作
管理唯一集合:
public class TagService(SmartRedisService redis)
{
public async Task AddTags(string userId, params string[] tags)
{
await redis.Set.AddAsync($"user:{userId}:tags", tags);
}
public async Task<string[]> GetTags(string userId)
{
return await redis.Set.MembersAsync($"user:{userId}:tags");
}
}
5. 有序集合操作
处理排名数据:
public class LeaderboardService(SmartRedisService redis)
{
public async Task AddScore(string userId, double score)
{
await redis.SortedSet.AddAsync("leaderboard", userId, score);
}
public async Task<Dictionary<string, double>> GetTopPlayers(int count)
{
return await redis.SortedSet.RangeByRankAsync("leaderboard", 0, count - 1, Order.Descending);
}
}
6. 流操作
处理消息流:
public class EventService(SmartRedisService redis)
{
public async Task PublishEvent(string eventType, Dictionary<string, string> data)
{
await redis.Stream.AddAsync($"events:{eventType}", data);
}
public async Task<StreamEntry[]> ReadEvents(string eventType, string groupName, string consumerName)
{
return await redis.Stream.ReadGroupAsync($"events:{eventType}", groupName, consumerName);
}
}
7. 分布式锁
实现分布式锁定:
public class OrderService(SmartRedisService redis)
{
public async Task ProcessOrder(string orderId)
{
var lockKey = $"order:lock:{orderId}";
var acquired = await redis.Lock.AcquireAsync(lockKey, TimeSpan.FromSeconds(30));
if (!acquired)
{
throw new InvalidOperationException("订单正在被其他实例处理");
}
try
{
await ProcessOrderInternal(orderId);
}
finally
{
await redis.Lock.ReleaseAsync(lockKey);
}
}
}
8. 原子计数器
实现分布式计数器:
public class CounterService(SmartRedisService redis)
{
public async Task<long> IncrementViewCount(string articleId)
{
return await redis.Counter.IncrementAsync($"article:{articleId}:views");
}
public async Task<long> GetViewCount(string articleId)
{
return await redis.Counter.GetAsync($"article:{articleId}:views");
}
}
9. 发布订阅
实现发布/订阅消息:
public class NotificationService(SmartRedisService redis)
{
public NotificationService(SmartRedisService redis)
{
redis.SubscribeReceived += OnMessageReceived;
}
private void OnMessageReceived(string channel, string message)
{
Console.WriteLine($"在 {channel} 收到消息: {message}");
}
public async Task SubscribeToNotifications()
{
await redis.Subscribe.SubscribeAsync("notifications");
}
public async Task PublishNotification(string message)
{
await redis.Subscribe.PublishAsync("notifications", message);
}
}
10. 管道操作
批量操作以提升性能:
public class BatchService(SmartRedisService redis)
{
public async Task BatchUpdate(Dictionary<string, string> data)
{
var batch = redis.GetDatabase().CreateBatch();
var tasks = data.Select(kv =>
batch.StringSetAsync(kv.Key, kv.Value)
).ToArray();
batch.Execute();
await Task.WhenAll(tasks);
}
}
核心模块
| 模块 | 功能描述 | 示例方法 |
|---|---|---|
| RedisKey | 键管理操作 | ExistsAsync, DeleteAsync, ExpireAsync |
| RedisString | 字符串/对象存储 | SetAsync<T>, GetAsync<T>, SetExpiryAsync |
| RedisHash | 哈希表字段操作 | SetAsync, GetAsync<T>, GetAllAsync<T> |
| RedisList | 队列/栈操作 | LeftPushAsync, RightPopAsync, RangeAsync |
| RedisSet | 唯一集合操作 | AddAsync, MembersAsync, RemoveAsync |
| RedisSortedSet | 排名集合操作 | AddAsync, RangeByRankAsync, RangeByScoreAsync |
| RedisStream | 消息流处理 | AddAsync, ReadGroupAsync, CreateGroupAsync |
| RedisLock | 分布式锁 | AcquireAsync, ReleaseAsync, IsAcquiredAsync |
| RedisCounter | 原子计数器 | IncrementAsync, DecrementAsync, GetAsync |
| RedisSubscribe | 发布订阅 | PublishAsync, SubscribeAsync, UnsubscribeAsync |
配置选项
public class RedisOptions
{
public string Server { get; set; }
public string Prefix { get; set; }
public int ConnectTimeout { get; set; } = 15000;
public int SyncTimeout { get; set; } = 5000;
public bool AbortOnConnectFail { get; set; } = false;
public int ConnectRetry { get; set; } = 3;
public JsonSerializerOptions JsonSerializerOptions { get; set; }
}
最佳实践
键命名规范
- 使用格式
业务:环境:实体:ID - 示例:
orders:prod:2024,users:dev:session:12345
- 使用格式
批量操作
- 使用管道进行批量操作以减少往返次数
- 示例: 在单个操作中批量设置多个键
异常处理
try { await redis.String.SetAsync(...); } catch (RedisConnectionException ex) { // 处理连接错误 } catch (RedisTimeoutException ex) { // 处理超时错误 }连接字符串
- 始终包含
abortConnect=false以允许自动重连 - 根据网络条件设置适当的超时值
- 始终包含
内存管理
- 为缓存数据设置适当的过期时间
- 使用
ExpireAsync设置键的 TTL
注意事项
- 连接字符串: 必须包含
abortConnect=false以支持自动重连 - 安全性: 敏感配置(如密码)应存储在安全的配置提供程序中
- 性能: 避免在热路径中频繁创建连接
- 发布订阅: 处理发布/订阅操作中的消息积压场景
- 流: Redis Stream 操作需要 Redis 5.0 或更高版本
- 线程安全:
SmartRedisService实例是线程安全的,可以在整个应用程序中共享
Developed by zenglei
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Microsoft.Extensions.DependencyInjection (>= 9.0.0)
- StackExchange.Redis (>= 2.10.14)
-
net8.0
- Microsoft.Extensions.DependencyInjection (>= 9.0.0)
- StackExchange.Redis (>= 2.10.14)
-
net9.0
- Microsoft.Extensions.DependencyInjection (>= 9.0.0)
- StackExchange.Redis (>= 2.10.14)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 4.2.0 | 82 | 2/14/2026 |
| 4.1.1 | 93 | 2/11/2026 |
| 4.1.0 | 97 | 2/9/2026 |
| 4.0.1 | 104 | 12/30/2025 |
| 4.0.0 | 199 | 4/5/2025 |
| 3.2.0 | 197 | 3/27/2025 |
| 3.1.1 | 201 | 3/16/2025 |
| 3.1.0 | 149 | 2/26/2025 |
| 3.0.1 | 171 | 2/15/2025 |
| 3.0.0 | 175 | 2/15/2025 |
| 2.1.2 | 175 | 2/13/2025 |
| 2.1.1 | 166 | 2/9/2025 |
| 2.1.0 | 163 | 12/29/2024 |
| 2.0.2 | 200 | 12/7/2024 |
| 2.0.1 | 178 | 12/7/2024 |
| 2.0.0 | 163 | 11/26/2024 |
| 1.2.0 | 175 | 10/31/2024 |
| 1.1.0.1 | 179 | 10/9/2024 |
| 1.1.0 | 188 | 9/27/2024 |
| 1.0.0.1 | 207 | 9/26/2024 |