.net core mqtt客户端Shiny.Mqtt库的使用
一、说明
Shiny.Mqtt是一个mqtt客户端,基于新生命团队newlife.mqtt的封装,推荐使用workerservice项目使用,支持.net core3,.net5,.net6
二、安装
nuget直接搜索Shiny.Mqtt安装
这是mqtt客户端注入的代码,可以看到,它是根据配置文件获取mqtt配置的
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
namespace Shiny.Mqtt
{
///
/// Mqtt客户端扩展类
///
public static class MqttClientSetup
{
///
/// 添加Mqtt客户端服务
///
///
///
///
public static void AddMqttClient(this IServiceCollection services, IConfiguration configuration, string section = "MqttSetting")
{
if (services == null) throw new ArgumentNullException(nameof(services));
var config = configuration.GetSection(section);
services.Configure(config);
services.AddSingleton();
}
}
}
所以我们的配置文件要这么配,这里MqttSetting可以改成其他的,只要在注入的方法里section参数改成对应的名称就行了
{
"MqttSetting": {
"Host": "192.168.1.1",
"Port": 1883,
"UserName": "xxx",
"SecretKey": "xxx",
"ClientId": "xxx",
"Topic": "xxx"
}
}
我实在workerservice里使用的mqtt客户端,所以我是这么注入的
三、使用
直接通过构造函数注入
直接通过getclient方法订阅消息
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var topic = "Shiny/#";
_logger.LogInformation($"开始订阅频道:{topic}:" + DateTime.Now);
////接收上线消息
await mqttClientService.GetClient().SubscribeAsync(topic, (e) =>
{
Console.WriteLine("收到一条消息来自主题:" + "=>" + e.Topic);
});
}