.NET MQTT客户端SimpleMQTT的使用
一、说明
MQTT客户端组件.NET Core版本,基于新生命团队NewLife.MQTT的单例模式封装,支持.net core3,.net6/7
Github地址:https://github.com/zxzyjs/SimpleMQTT.git
Gitee地址:https://gitee.com/zxzyjs/SimpleMQTT.git
二、安装
1.直接下载源码添加到现有项目,添加项目引用
2.nuget直接搜索SimpleMQTT安装
三、注入
默认读取配置文件下的MqttSetting节点,当然也可以自定义节点名
{
"MqttSettings": {
"Host": "192.168.1.1",
"Port": 1883,
"UserName": "xxx",
"SecretKey": "xxx",
"ClientId": "xxx",
}
}
支持多客户端配置,只需在每个客户端配置上加上Name属性即可
"MqttSettings": [
{
"Name": "mqtt1",
"Host": "127.0.0.1",
"Port": 1883,
"UserName": "admin",
"SecretKey": "admin",
"ClientId": "admin"
},
{
"Name": "mqtt2",
"Host": "127.0.0.2",
"Port": 1883,
"UserName": "admin",
"SecretKey": "admin",
"ClientId": "admin"
}
]
除了上述配置外,还支持其他属性配置
/// <summary>
/// mqtt客户端配置
/// </summary>
public class MqttClientConfig
{
/// <summary>
/// 客户端名称
/// </summary>
public string Name { get; set; } = "Mqtt";
/// <summary>
/// 主机地址
/// </summary>
public string Host { get; set; }
/// <summary>
/// 端口
/// </summary>
public int Port { get; set; }
/// <summary>
/// 用户名
/// </summary>
public string UserName { get; set; }
/// <summary>
/// 秘钥
/// </summary>
public string SecretKey { get; set; }
/// <summary>
/// 客户端ID
/// </summary>
public string ClientId { get; set; }
/// <summary>
/// 心跳
/// </summary>
public int KeepAlive { get; set; } = 60;
/// <summary>
/// 是否自动重连,默认True
/// </summary>
public bool Reconnect { get; set; } = true;
/// <summary>
/// 是否清除会话,默认True
/// </summary>
public bool CleanSession { get; set; } = true;
/// <summary>
/// 超时。默认15000ms
/// </summary>
public int Timeout { get; set; } = 15000;
/// <summary>
/// 是否进行SSL连接
/// </summary>
public bool UseSSL { get; set; } = false;
}
以下是注入代码,请自行选择注入方式
查看代码
/// <summary>
/// 添加Mqtt客户端服务
/// </summary>
/// <param name="services"></param>
/// <exception cref="ArgumentNullException"></exception>
public static void AddMqttClientManager(this IServiceCollection services)
{
if (services == null) throw new ArgumentNullException(nameof(services));
services.AddSingleton<IMqttClientManager, MqttClientManager>();
}
/// <summary>
/// 添加Mqtt客户端服务
/// </summary>
/// <param name="services"></param>
/// <param name="configuration">IConfiguration</param>
/// <param name="section">配置文件节点</param>
/// <param name="start">立即启动</param>
/// <exception cref="ArgumentNullException"></exception>
public static void AddMqttClientManager(this IServiceCollection services, IConfiguration configuration, string section = "MqttSetting", bool start = true)
{
if (services == null) throw new ArgumentNullException(nameof(services));
MqttClientConfig config = new MqttClientConfig();
configuration.GetSection(section).Bind(config);//获取配置
services.AddSingleton<IMqttClientManager, MqttClientManager>(x => new MqttClientManager(config, start));
}
/// <summary>
/// 添加Mqtt客户端服务
/// </summary>
/// <param name="services"></param>
/// <param name="config">mqtt配置</param>
/// <param name="start">立即启动</param>
/// <exception cref="ArgumentNullException"></exception>
public static void AddMqttClientManager(this IServiceCollection services, MqttClientConfig config, bool start = true)
{
if (services == null) throw new ArgumentNullException(nameof(services));
services.AddSingleton<IMqttClientManager, MqttClientManager>(x => new MqttClientManager(config, start));
}
/// <summary>
/// 添加Mqtt客户端服务
/// </summary>
/// <param name="services"></param>
/// <param name="configs">mqtt配置</param>
/// <param name="start">立即启动</param>
/// <exception cref="ArgumentNullException"></exception>
public static void AddMqttClientManager(this IServiceCollection services, List<MqttClientConfig> configs, bool start = true)
{
if (services == null) throw new ArgumentNullException(nameof(services));
services.AddSingleton<IMqttClientManager, MqttClientManager>(x => new MqttClientManager(configs, start));
}
}
我一般在workerservice项目中使用,所以这么注册就行了
IHost host = Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddMqttClientManager();//第一种
//services.AddMqttClientManager(hostContext.Configuration, "xxx");//第二种
})
四、使用
4.1采用注入的方式(推荐)
直接构造函数注入即可
private readonly MqttClient mqttClient;
public Worker(ILogger<Worker> logger, IMqttClientManager mqttClientManager)
{
_logger = logger;
mqttClient = mqttClientManager.GetClient();
}
如果是多个客户端
private readonly List<MqttClient> mqttClients;
public Worker(ILogger<Worker> logger, IMqttClientManager mqttClientManager)
{
_logger = logger;
mqttClients = mqttClientManager.GetClients();
}
4.2采用New的方式
MqttClientConfig config = new MqttClientConfig() { Host = "xx", Port = 1883 };
var mqttManager = new MqttClientManager(config);
mqttManager.GetClient().Disconnected += (object? sender, EventArgs e) =>
{
Console.WriteLine("断开");
};
mqttManager.GetClient().Connected += (object? sender, EventArgs e) =>
{
Console.WriteLine("连接");
};
mqttManager.StartClient();
本文来自博客园,作者:HuTiger,转载请注明原文链接:https://www.cnblogs.com/huguodong/p/16991947.html,欢迎加入qq群927460240学习讨论