HMENetCore.Redis
6.0.48
.NET 6.0
This package targets .NET 6.0. The package is compatible with this framework or higher.
.NET Standard 2.1
This package targets .NET Standard 2.1. The package is compatible with this framework or higher.
dotnet add package HMENetCore.Redis --version 6.0.48
NuGet\Install-Package HMENetCore.Redis -Version 6.0.48
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="HMENetCore.Redis" Version="6.0.48" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="HMENetCore.Redis" Version="6.0.48" />
<PackageReference Include="HMENetCore.Redis" />
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add HMENetCore.Redis --version 6.0.48
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: HMENetCore.Redis, 6.0.48"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package HMENetCore.Redis@6.0.48
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=HMENetCore.Redis&version=6.0.48
#tool nuget:?package=HMENetCore.Redis&version=6.0.48
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
HMENetCore.Redis
简介
HMENetCore.Redis
是一个基于 StackExchange.Redis 的 Redis 高性能客户端组件库,提供了丰富的 Redis 数据结构和操作方法的封装,支持同步和异步操作,内置连接池管理和重试机制,简化了 .NET 应用中 Redis 的使用。
功能特性
- 支持多种 Redis 数据结构:String, Hash, List, Set, SortedSet 等
- 同步/异步方法支持
- 自动连接管理和重试机制
- 内置 JSON 序列化/反序列化
- 分布式锁实现*
- 发布订阅模式支持*
- 键前缀管理
- 多数据库支持
- 基数统计(HyperLogLog)支持
.NET支持
- 跨平台支持: Supports .NET Standard 2.1, .NET 6, .NET 8, and .NET 9.
安装
dotnet add package HMENetCore.Redis --version 6.0.48
配置连接
添加配置到 appsettings.json
:
{
"RedisConfig": {
"ConnectionString": [ "192.168.1.222:6379" ],
"UserName": "",
"Password": "HmeTestRedisPasswd",
"DatabaseId": 1
}
}
服务注册
var redisConfig = Configuration.GetSection("RedisConfig").Get<RedisConfig>();
builder.Services.AddRedisSetup(redisConfig);
基本使用
字符串(String)操作
public class StringOperationsService
{
private readonly IRedisClient _redisClient;
public StringOperationsService(IRedisClient redisClient)
{
_redisClient = redisClient;
}
// 设置字符串值
public async Task SetStringValueAsync()
{
var key = "test:string";
var value = "Hello Redis";
await _redisClient.StringSetAsync(key, value, TimeSpan.FromMinutes(5));
}
// 获取字符串值
public async Task<string> GetStringValueAsync()
{
var key = "test:string";
return await _redisClient.StringGetAsync(key);
}
// 原子性递增
public async Task<double> IncrementValueAsync()
{
var key = "test:counter";
return await _redisClient.StringIncrementAsync(key, 1);
}
// 获取或创建(如果不存在)
public async Task<string> GetOrCreateAsync()
{
var key = "test:getorcreate";
return await _redisClient.StringGetOrCreateAsync(key,
async () =>
{
// 模拟耗时操作
await Task.Delay(100);
return "Created value";
},
TimeSpan.FromMinutes(1));
}
}
哈希(Hash)操作
public class HashOperationsService
{
private readonly IRedisClient _redisClient;
public HashOperationsService(IRedisClient redisClient)
{
_redisClient = redisClient;
}
// 设置哈希字段
public async Task SetHashFieldAsync()
{
var key = "user:1001";
await _redisClient.HashSetAsync(key, "name", "张三");
await _redisClient.HashSetAsync(key, "age", 30);
}
// 批量设置哈希字段
public async Task BatchSetHashFieldsAsync()
{
var key = "user:1002";
var fields = new List<KeyValuePair<string, object>>
{
new KeyValuePair<string, object>("name", "李四"),
new KeyValuePair<string, object>("age", 25),
new KeyValuePair<string, object>("email", "lisi@example.com")
};
await _redisClient.HashSetAsync(key, fields);
}
// 获取哈希字段
public async Task<string> GetHashFieldAsync()
{
var key = "user:1001";
return await _redisClient.HashGetAsync<string>(key, "name");
}
// 获取整个哈希
public async Task<Dictionary<string, string>> GetAllHashFieldsAsync()
{
var key = "user:1001";
var values = await _redisClient.HashGetAllAsync<string>(key);
return values.ToDictionary(x => x.Key, x => x.Value);
}
}
列表(List)操作
public class ListOperationsService
{
private readonly IRedisClient _redisClient;
public ListOperationsService(IRedisClient redisClient)
{
_redisClient = redisClient;
}
// 从左侧推入元素
public async Task PushLeftAsync()
{
var key = "test:list";
await _redisClient.ListLeftPushAsync(key, "item1");
await _redisClient.ListLeftPushAsync(key, "item2");
}
// 从右侧推入元素
public async Task PushRightAsync()
{
var key = "test:list";
await _redisClient.ListRightPushAsync(key, "item3");
}
// 从右侧弹出元素
public async Task<string> PopRightAsync()
{
var key = "test:list";
return await _redisClient.ListRightPopAsync<string>(key);
}
// 获取列表范围
public async Task<List<string>> GetListRangeAsync()
{
var key = "test:list";
return await _redisClient.ListRangeAsync<string>(key);
}
}
发布订阅(Pub/Sub)
public class PubSubService
{
private readonly IRedisClient _redisClient;
public PubSubService(IRedisClient redisClient)
{
_redisClient = redisClient;
}
// 订阅消息
public void SubscribeMessages()
{
_redisClient.Subscribe("test:channel", (channel, message) =>
{
Console.WriteLine($"Received message: {message} from channel: {channel}");
});
}
// 发布消息
public async Task PublishMessageAsync()
{
var message = new { Time = DateTime.Now, Content = "Hello from Pub/Sub" };
await _redisClient.PublishAsync("test:channel", message);
}
}
分布式锁
public class DistributedLockService
{
private readonly IRedisClient _redisClient;
public DistributedLockService(IRedisClient redisClient)
{
_redisClient = redisClient;
}
public async Task ProcessWithLockAsync()
{
var lockKey = "resource:lock";
var lockTimeout = TimeSpan.FromSeconds(30);
// 使用锁执行操作
await using (var redisLock = new RedisDistributedLockAsync(
_redisClient.GetDatabase(),
lockKey,
lockTimeout))
{
try
{
await redisLock.ExecuteWithLockAsync(async () =>
{
// 模拟耗时操作
await Task.Delay(1000);
Console.WriteLine("Processing under lock...");
});
}
catch (Exception ex)
{
Console.WriteLine($"Lock processing failed: {ex.Message}");
}
}
}
}
事务支持
public class TransactionService
{
private readonly IRedisClient _redisClient;
public TransactionService(IRedisClient redisClient)
{
_redisClient = redisClient;
}
public async Task ExecuteTransactionAsync()
{
var db = _redisClient.GetDatabase();
var transaction = db.CreateTransaction();
try
{
// 添加事务操作
transaction.AddCondition(Condition.KeyNotExists("transaction:key"));
transaction.StringSetAsync("transaction:key", "value");
transaction.StringIncrementAsync("transaction:counter");
// 执行事务
bool committed = await transaction.ExecuteAsync();
if (committed)
{
Console.WriteLine("Transaction committed successfully");
}
else
{
Console.WriteLine("Transaction failed to commit");
}
}
catch (Exception ex)
{
Console.WriteLine($"Transaction error: {ex.Message}");
}
}
}
键管理
public class KeyManagementService
{
private readonly IRedisClient _redisClient;
public KeyManagementService(IRedisClient redisClient)
{
_redisClient = redisClient;
}
// 设置键过期时间
public async Task SetKeyExpireAsync()
{
var key = "temp:data";
await _redisClient.StringSetAsync(key, "some value");
await _redisClient.KeyExpireAsync(key, TimeSpan.FromMinutes(10));
}
// 检查键是否存在
public async Task<bool> KeyExistsAsync()
{
var key = "temp:data";
return await _redisClient.KeyExistsAsync(key);
}
// 模糊查询键
public async Task<List<string>> SearchKeysAsync()
{
var pattern = "test:*";
var keys = await _redisClient.KeyFuzzyQueryAsync(pattern);
return keys.Select(k => (string)k).ToList();
}
}
常见问题
Q1: 如何处理 Redis 连接断开的情况?
RedisClient 实现了自动重连机制,当检测到连接断开时会自动尝试重新连接
public async Task<T> ExecuteWithRetryAsync<T>(Func<Task<T>> action, int maxRetry = 3)
{
for (int i = 0; i < maxRetry; i++)
{
try
{
return await action();
}
catch (RedisConnectionException ex) when (i < maxRetry - 1)
{
await Task.Delay(1000 * (i + 1)); // 指数退避
}
}
throw new Exception("Operation failed after multiple retries");
}
Q2: 如何实现 Redis 集群支持?
只需在配置中提供多个节点地址
var redisConfig = new RedisConfig
{
ConnectionString = new List<string>
{
"node1:6379",
"node2:6379",
"node3:6379"
},
// 其他配置...
};
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net5.0 was computed. net5.0-windows was computed. net6.0 is compatible. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. 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 was computed. 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. |
.NET Core | netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
.NET Standard | netstandard2.1 is compatible. |
MonoAndroid | monoandroid was computed. |
MonoMac | monomac was computed. |
MonoTouch | monotouch was computed. |
Tizen | tizen60 was computed. |
Xamarin.iOS | xamarinios was computed. |
Xamarin.Mac | xamarinmac was computed. |
Xamarin.TVOS | xamarintvos was computed. |
Xamarin.WatchOS | xamarinwatchos was computed. |
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
-
.NETStandard 2.1
- HMENetCore (>= 6.0.48)
- Microsoft.Extensions.Options (>= 9.0.8)
- Polly (>= 8.6.2)
- StackExchange.Redis (>= 2.8.58)
-
net6.0
- HMENetCore (>= 6.0.48)
- Microsoft.Extensions.Options (>= 8.0.2)
- Polly (>= 8.6.2)
- StackExchange.Redis (>= 2.8.58)
-
net8.0
- HMENetCore (>= 6.0.48)
- Microsoft.Extensions.Options (>= 9.0.8)
- Polly (>= 8.6.2)
- StackExchange.Redis (>= 2.8.58)
-
net9.0
- HMENetCore (>= 6.0.48)
- Microsoft.Extensions.Options (>= 9.0.8)
- Polly (>= 8.6.2)
- StackExchange.Redis (>= 2.8.58)
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 |
---|---|---|
6.0.48 | 11 | 8/11/2025 |
6.0.47 | 11 | 8/11/2025 |
6.0.46 | 164 | 8/7/2025 |
6.0.45 | 120 | 7/16/2025 |
6.0.42 | 146 | 6/18/2025 |
6.0.40 | 276 | 6/10/2025 |
6.0.39 | 237 | 5/15/2025 |
6.0.37 | 149 | 5/7/2025 |
6.0.36 | 141 | 4/27/2025 |
6.0.32 | 169 | 4/9/2025 |
6.0.31 | 155 | 3/17/2025 |
6.0.30 | 121 | 2/19/2025 |
6.0.20 | 110 | 2/5/2025 |
6.0.18 | 114 | 1/6/2025 |
6.0.12 | 133 | 12/9/2024 |
6.0.9 | 117 | 11/28/2024 |
6.0.8 | 114 | 11/15/2024 |
6.0.6 | 132 | 10/9/2024 |
6.0.5 | 134 | 9/12/2024 |
6.0.3 | 138 | 9/9/2024 |
6.0.1 | 165 | 8/16/2024 |