HMEFramework.Redis
2.8.0
dotnet add package HMEFramework.Redis --version 2.8.0
NuGet\Install-Package HMEFramework.Redis -Version 2.8.0
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="HMEFramework.Redis" Version="2.8.0" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="HMEFramework.Redis" Version="2.8.0" />
<PackageReference Include="HMEFramework.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 HMEFramework.Redis --version 2.8.0
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: HMEFramework.Redis, 2.8.0"
#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 HMEFramework.Redis@2.8.0
#: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=HMEFramework.Redis&version=2.8.0
#tool nuget:?package=HMEFramework.Redis&version=2.8.0
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
HMEFramework.Redis
简介
HMEFramework.Redis 是一个基于 StackExchange.Redis 的 Redis 高性能客户端组件库,提供了丰富的 Redis 数据结构和操作方法的封装,支持同步和异步操作,内置连接池管理和重试机制,简化了 .NET 应用中 Redis 的使用。
功能特性
- 支持多种 Redis 数据结构:String, Hash, List, Set, SortedSet 等
- 同步/异步方法支持
- 自动连接管理和重试机制
- 内置 JSON 序列化/反序列化
- 分布式锁实现*
- 发布订阅模式支持*
- 键前缀管理
- 多数据库支持
- 基数统计(HyperLogLog)支持
运行环境
- 跨平台支持: Supports .NET Standard 2.1, .NET 6+.
安装
dotnet add package HMEFramework.Redis
配置连接
添加配置到 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 was computed. 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 was computed. 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 was computed. 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
- HMEFramework (>= 2.8.0)
- Microsoft.Extensions.Options (>= 10.0.2)
- Polly (>= 8.6.5)
- StackExchange.Redis (>= 2.10.1)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.