Hyz.MqttClient
1.0.0
There is a newer version of this package available.
See the version list below for details.
See the version list below for details.
dotnet add package Hyz.MqttClient --version 1.0.0
NuGet\Install-Package Hyz.MqttClient -Version 1.0.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="Hyz.MqttClient" Version="1.0.0" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Hyz.MqttClient" Version="1.0.0" />
<PackageReference Include="Hyz.MqttClient" />
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 Hyz.MqttClient --version 1.0.0
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: Hyz.MqttClient, 1.0.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 Hyz.MqttClient@1.0.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=Hyz.MqttClient&version=1.0.0
#tool nuget:?package=Hyz.MqttClient&version=1.0.0
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
Hyz.MqttClient
基于 Roslyn 源码生成器的 MQTT 客户端库,编译时自动生成订阅代码,零运行时反射。
安装
dotnet add package Hyz.MqttClient
快速开始
1. 注册服务
using Hyz.MqttClient.Extensions;
builder.Services.AddHyzMqttClientConfig(options =>
{
options.Server = "localhost";
options.Port = 1883;
options.ClientId = "MyMqttClient";
});
builder.Services.AddHyzMqttClient();
builder.Services.AddHyzMqttServices();
2. 定义消息处理器
using Hyz.MqttClient.Core.Attributes;
public class MqttHandlers
{
// 处理字符串消息
[MqttSubscribe("topic/string")]
public async Task HandleStringMessage(string payload)
{
Console.WriteLine($"收到: {payload}");
}
// 处理强类型消息(自动反序列化)
[MqttSubscribe("topic/json", MessageType = typeof(MyMessage))]
public async Task HandleJsonMessage(MyMessage message)
{
Console.WriteLine($"收到: {message.Content}");
}
}
public class MyMessage
{
public string Content { get; set; }
}
3. 连接并订阅
var mqttClient = sp.GetRequiredService<IMqttClientHelper>();
await mqttClient.ConnectFromConfigAsync();
await sp.StartAllHyzMqttSubscriptions();
// 发布消息
await mqttClient.PublishAsync("topic/string", "Hello MQTT!");
核心特性
| 特性 | 说明 |
|---|---|
[MqttSubscribe] |
方法级特性,标记即订阅 |
| 源码生成器 | 编译时生成订阅代码,零反射 |
| 自动反序列化 | 指定 MessageType 自动 JSON 反序列化 |
| 主题通配符 | 支持 + 单级、# 多级通配符 |
| 多连接 | 通过 ConnectionName 管理多连接 |
| 自动重连 | 内置指数退避重连策略 |
特性详解
MqttSubscribeAttribute
[MqttSubscribe(
topic: "device/+/data", // 必填:订阅主题
qos: MqttQoS.AtLeastOnce, // QoS 等级,默认 AtMostOnce
connectionName: "server1", // 连接名称,默认使用默认连接
messageType: typeof(MyMessage), // 消息类型,用于自动反序列化
enableAutoDeserialization: true // 是否启用自动反序列化
)]
public async Task HandleMessage(MyMessage message) { }
方法参数类型:
| 参数类型 | 处理方式 |
|---|---|
string |
原始字符串 payload |
MqttApplicationMessageReceivedEventArgs |
完整事件参数 |
| 其他类型 | 配合 MessageType 自动反序列化 |
QoS 等级
public enum MqttQoS
{
AtMostOnce = 0, // 最多一次
AtLeastOnce = 1, // 至少一次
ExactlyOnce = 2 // 恰好一次
}
完整示例
基本发布/订阅
using Hyz.MqttClient.Core.Attributes;
using Hyz.MqttClient.Extensions;
using MQTTnet.Protocol;
var builder = WebApplication.CreateBuilder(args);
// 注册
builder.Services.AddHyzMqttClientConfig(options =>
{
options.Server = "localhost";
options.Port = 1883;
});
builder.Services.AddHyzMqttClient();
builder.Services.AddHyzMqttServices();
var app = builder.Build();
// 连接并订阅
var mqttClient = app.Services.GetRequiredService<IMqttClientHelper>();
await mqttClient.ConnectFromConfigAsync();
await app.Services.StartAllHyzMqttSubscriptions();
// 发布
await mqttClient.PublishAsync("topic/test", "Hello!", MqttQualityOfServiceLevel.AtMostOnce);
app.Run();
// 处理器
public class MyHandler
{
[MqttSubscribe("topic/test")]
public async Task Handle(string payload)
{
Console.WriteLine(payload);
}
}
强类型消息
public class SensorData
{
public string DeviceId { get; set; }
public double Temperature { get; set; }
}
public class SensorHandler
{
[MqttSubscribe("sensor/+/data", MessageType = typeof(SensorData))]
public async Task Handle(SensorData data)
{
Console.WriteLine($"设备 {data.DeviceId}: {data.Temperature}°C");
}
}
// 发布时需要传递 JSON 字符串
var json = JsonSerializer.Serialize(new SensorData { DeviceId = "001", Temperature = 25.5 });
await mqttClient.PublishAsync("sensor/001/data", json);
多连接
// 注册多个连接
builder.Services.AddHyzMqttClientConfig("server1", options =>
{
options.Server = "mqtt1.example.com";
});
builder.Services.AddHyzMqttClientConfig("server2", options =>
{
options.Server = "mqtt2.example.com";
});
builder.Services.AddHyzMqttClient();
// 处理器指定连接
public class MultiHandler
{
[MqttSubscribe("topic/a", ConnectionName = "server1")]
public async Task HandleA(string payload) { }
[MqttSubscribe("topic/b", ConnectionName = "server2")]
public async Task HandleB(string payload) { }
}
// 发布到指定连接
mqttClient.Use("server1").PublishAsync("topic/a", "message");
WebSocket 连接
builder.Services.AddHyzMqttClientConfig(options =>
{
options.WebSocketUrl = "wss://mqtt.example.com/mqtt";
});
MQTT 5.0 用户属性
var properties = new List<MqttUserProperty>
{
new("correlation-id", Guid.NewGuid().ToString())
};
await mqttClient.PublishAsync(
"topic/data",
jsonPayload,
MqttQualityOfServiceLevel.AtLeastOnce,
retain: false,
properties);
MqttConfig 配置
| 属性 | 默认值 | 说明 |
|---|---|---|
Server |
- | MQTT 服务器地址 |
Port |
1883 |
端口号 |
ClientId |
- | 客户端 ID |
Username |
- | 用户名 |
Password |
- | 密码 |
CleanSession |
true |
是否清除会话 |
WebSocketUrl |
- | WebSocket URL(设置后优先使用) |
KeepAlivePeriod |
60 秒 |
保活周期 |
ConnectionTimeoutSeconds |
10 |
连接超时 |
EnableAutoReconnect |
true |
是否启用自动重连 |
ReconnectDelay |
5 秒 |
重连延迟 |
MaxReconnectAttempts |
20 |
最大重连次数(0=无限) |
ReconnectStrategy |
ExponentialBackoff |
重连策略 |
MaxReconnectDelay |
300 秒 |
最大重连延迟 |
IMqttClientHelper 主要方法
| 方法 | 说明 |
|---|---|
ConnectFromConfigAsync() |
从配置连接 |
ConnectAsync(server, port, clientId?, username?, password?) |
直接连接 |
ConnectWebSocketAsync(url) |
WebSocket 连接 |
PublishAsync(topic, payload, qos?, retain?) |
发布消息 |
SubscribeAsync(topic, qos?) |
订阅主题 |
UnsubscribeAsync(topic) |
取消订阅 |
DisconnectAsync() |
断开连接 |
Use(connectionName) |
切换连接(链式调用) |
属性: IsConnected、IsReconnecting、ClientId
事件: MessageReceived、ConnectionStateChanged
依赖项
| 包 | 版本 |
|---|---|
| MQTTnet | 5.0.1.1416 |
| System.Text.Json | 10.0.1 |
| Microsoft.Extensions.* | 8.0.0 / 9.0.0 |
| Microsoft.CodeAnalysis.CSharp | 4.11.0(编译时) |
许可证
MIT
| 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. |
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
-
net10.0
- Hyz.MqttClient.Core (>= 1.0.0)
-
net8.0
- Hyz.MqttClient.Core (>= 1.0.0)
-
net9.0
- Hyz.MqttClient.Core (>= 1.0.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.