如何像使用AspNetCore中的Controllers 和 Actions一样处理MQTT消息

在物联网项目中, 处理MQTT的topic时费工费力, 代码一团乱, 什么才是最好的姿势?这里面我们极力介绍 MQTTnet.AspNetCore.Routing  项目,MQTTnet AspNetCore Routing 是https://github.com/Atlas-LiftTech/MQTTnet.AspNetCore.AttributeRouting 的分支项目。这个组件是通过MQTTnet 实现了定义控制类和属性来路由处理消息的topic , 就像Asp.Net Core 的WebApi 写法一样简单容易。 

为什么要用这个库?

这个库完全是一个MQTTnet的可选扩展 ,但如果你恰好有如下需求:

  • 你的主要需求是在服务器上验证和处理MQTT消息。

  • 你的服务器并不主要用于向客户端发送消息。 

  • 您喜欢以类似于 AspNetCore 和 WebAPI 的方式将消息处理逻辑封装在控制器中。

您可以自己使用 MQTTnet 委托直接执行此插件执行的所有操作。但是,随着您为验证或处理传入消息而编写的逻辑量增加,将逻辑组织到控制器中的能力开始变得更加有意义。该库有助于组织该代码,并将依赖项注入框架整合到MQTTnet中。

功能

  • 将传入消息逻辑封装在控制器中

  • 在 MQTT 逻辑中使用 AspNetCore 中熟悉的范例(Controllers 和 Actions)

  • 在 AspNetCore 项目中使用现有的 ServiceProvider 实现对依赖注入的一流支持

  • 支持控制器上的同步和async/await操作

  • 与任何其他 MQTTnet 选项一起使用

性能说明

此库尚未针对非常高负载的环境进行测试。确保在生产中使用之前执行自己的负载测试。欢迎所有性能改进 PR。

支持的框架

  • .NET Standard 2.0+

  • .NET Core 3.1+

支持的MQTT版本

  • 5.0.0

  • 3.1.1

  • 3.1.0

Nuget 和仓库地址

Nutget: https://www.nuget.org/packages/MQTTnet.AspNetCore.Routing/

https://gitee.com/IoTSharp/MQTTnet.AspNetCore.Routing

https://github.com/IoTSharp/MQTTnet.AspNetCore.Routing

使用方法

从nuget安装此包和MQTTnet。dotnet CLI:

dotnet add package MQTTnet.AspNetCore.Routing

 ASP.NET Core 6 MVC 配置示例

using MQTTnet.AspNetCore;
using MQTTnet.AspNetCore.Routing;var builder = WebApplication.CreateBuilder(args);
builder.WebHost.ConfigureKestrel(o =>{o.ListenAnyIP(iotaboardMqttSettings.Port, l => l.UseMqtt());o.ListenAnyIP(iotaboardHttpSettings.Port);}
);//配置MQTT服务
builder.Services.AddHostedMqttServerWithServices(o =>{// other configurationso.WithoutDefaultEndpoint();}).AddMqttConnectionHandler().AddConnections().AddMqttControllers( // <== NOTICE THIS PART/*默认情况下,所有控制类在这里都会被自动发现, 那么这里就是空的, 但是这里也提供了加入其他程序集的方法。*/); var app = builder.Build();app.MapControllers();
app.UseMqttServer(server => {  // other MqttServer configurations, for example client connect interceptsserver.WithAttributeRouting(app.Services, allowUnmatchedRoutes: false);
});
app.Run();

创建你的控制器, 集成 MqttBaseController 并添加方法像下面这样:

[MqttController]
[MqttRoute("[controller]")] // 指定控制类topic 。
public class MqttWeatherForecastController : MqttBaseController 
{private readonly ILogger<MqttWeatherForecastController> _logger;// Controllers支持完整的注入依赖, 就像AspNetCore 控制器一样。public MqttWeatherForecastController(ILogger<MqttWeatherForecastController> logger){_logger = logger;}//支持模板路由和类型定义就像AspNetCore一样。// Action 路由与控制器级别的路由前缀一起组成[MqttRoute("{zipCode:int}/temperature")]public Task WeatherReport(int zipCode){// 我们这里可以直接访问MqttContextif (zipCode != 90210) { MqttContext.CloseConnection = true; }// 我们可以直接访问原始数据var temperature = BitConverter.ToDouble(Message.Payload);_logger.LogInformation($"It's {temperature} degrees in Hollywood");// 规则判断if (temperature <= 0 || temperature >= 130){return BadMessage();}return Ok();}//我们也支持 FromPayload , 就像 AspNetCore中的FromBody 一样。[MqttRoute("viewmodel/{sender}")]public Task DeserializeViewModel(string sender, [FromPayload] SamplePayload payload){_logger.LogInformation("{Sender} says {Message}", sender, payload.Message);            return Accepted();}
}
public class SamplePayload
{public string Message { get; set; }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/281190.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

chrome 悬停大图插件_Google Chrome浏览器的悬停卡:我不想要的我最喜欢的新东西

chrome 悬停大图插件If you only have a handful of open tabs in Google Chrome, it’s easy to tell what they are. But as you start to collect more tabs (or make the window smaller), it gets harder. That’s where Hover Cards come in. 如果您在Google Chrome浏览器…

GitHub Codespaces 安装 .NET 7

本文主要介绍如何在 GitHub Codespaces 这个云上 IDE 环境中安装 .NET 7背景GitHub 的 Codespaces 可以让我们随时随地编写代码&#xff0c;一些简单的修改也非常方便快捷。特别是 .NET 7 发布后&#xff0c;一些可以直接升级的小项目只需要更改配置就可以了&#xff0c;我们可…

chrome怎么隐藏浏览器_如何使用Google Chrome的隐藏阅读器模式

chrome怎么隐藏浏览器Chrome 75 has a hidden “Reader” mode that strips web pages down to the bare minimum to make them easier to, well, read. But it’s not enabled by default—here’s how to get it now. Chrome 75具有隐藏的“阅读器”模式&#xff0c;可将网页…

angularjs中使用swiper时不起作用,最后出现空白位

controller.js中定义swipers指令&#xff1a; var moduleCtrl angular.module(newscontroller,[infinite-scroll,ngTouch,news.service]) .directive(swipers,swipers); swipers.$inject [$timeout]; function swipers($timeout) {return {restrict: "EA",scope: {…

使用Jupyter记事本记录和制作.NET可视化笔记

前言&#xff1a;对于记录笔记的工具特别多&#xff0c;不过对于程序员来说&#xff0c;记录笔记程序代码运行结果演示可以同时存在&#xff0c;无疑会极大增加我们的笔记的可读性和体验感。以前在写python的时候&#xff0c;使用jupyter的体验很好&#xff0c;所以此处做一个基…

火狐上如何使用谷歌翻译插件_将Google翻译功能添加到Firefox

火狐上如何使用谷歌翻译插件Are you looking for a quick no-fuss way to translate webpages? Then you will want to take a good look at the Translate extension for Firefox. 您是否正在寻找一种快速简便的方法来翻译网页&#xff1f; 然后&#xff0c;您将需要很好地了…

Android 4.X 系统加载 so 失败的原因分析

1 so 加载过程 so 加载的过程可以参考小米的系统工程师的文章loadLibrary动态库加载过程分析 2 问题分析 2.1 问题 年前项目里新加了一个 so库&#xff0c;但发现native 方法的找不到的 crash 好多&#xff0c;好些都是报了java.lang.unsatisfiedlinkerror native method not f…

桌面显示激活windows_愚蠢的怪胎技巧:如何在桌面上显示Windows版本

桌面显示激活windowsHave you ever noticed during all the beta releases of Windows, there’s always a Windows version on the desktop in the lower right-hand corner? Here’s how that “feature” is enabled or disabled. 您是否曾经在Windows的所有beta版本中都注…

服务网格:限流保护 (上)

背景限流是服务治理中保护服务的重要手段之一&#xff0c;也是最直接有效的手段&#xff0c;它可以保护服务不被瞬间的大流量冲垮&#xff0c;类似电路中的“保险丝”。在服务上线前&#xff0c;我们都会对服务进行基准测试&#xff0c;来了解可通过的最大“电流”。上面所说的…

博弈论进阶之Anti-SG游戏与SJ定理

前言 在上一节中&#xff0c;我们初步了解了一下SG函数与SG定理。 今天我们来分析一下SG游戏的变式——Anti-SG游戏以及它所对应的SG定理 首先从最基本的Anti-Nim游戏开始 Anti-Nim游戏是这样的 有两个顶尖聪明的人在玩游戏&#xff0c;游戏规则是这样的&#xff1a; 有\(n\)堆…

怎样取消outlook约会_快速提示:在Outlook 2010中设置和取消约会

怎样取消outlook约会Getting everyone in one place at the same time for appointments can be daunting at times. Outlook makes it easy to setup appointments and invite attendees as well, and here we look at doing it in Outlook 2010. 同时让每个人都集中在一个地方…

重视和解决 ABP 分布式事件乱序问题

ABP Framework 5.0 实现了单体应用场景下&#xff0c;收件箱和发件箱的事件严格顺序性。但在微服务或多数据库场景下&#xff0c;由于网络时延和设施效率的限制&#xff0c; 分布式事件将不再是 Linearizability [1] 的&#xff0c;因此必然会存在物理时间上的收件乱序。借用 D…

个人博客建站方案推荐

1.服务器选择 正值双十一来临之际各大服务器提供商又大量的优惠活动&#xff0c;各位要步入个人站长行列的小哥们时机要把握好了&#xff0c;我个人使用过阿里云的服务器&#xff0c;腾讯云的服务器&#xff0c;华为云的服务器。其实&#xff0c;个人感觉就放个博客&#xff0c…

linux系统下nginx安装目录和nginx.conf配置文件目录

linux系统下nginx安装目录和nginx.conf配置文件目录 1、查看nginx安装目录 输入命令 # ps -ef | grep nginx 返回结果包含安装目录 root 2662 1 0 07:12 ? 00:00:00 nginx: master process /usr/sbin/nginx 2、查看nginx.conf配置文件目录 输入命令 # nginx…

android启用hdcp_如何在Android上启用优先收件箱(和设置仅重要通知)

android启用hdcpYesterday Google released an updated Gmail application for Android 2.2 phones that supports the Priority Inbox feature—and more importantly, allows you to change your notifications to only alert you for important email. Let’s take a look. …

.Net CLR GC plan_phase二叉树和Brick_table

楔子Plan_Phase(GC的计划阶段)很早就接触了&#xff0c;但是后面一直没用到&#xff0c;忘记了&#xff0c;此次又用到了&#xff0c;几乎忘光了&#xff0c;费了很大力气理解它&#xff0c;记录下&#xff0c;以免又忘记了。主题计划阶段(plan_phase)主要就两个部分&#xff0…

Vijos p1484 ISBN号码

描述每一本正式出版的图书都有一个ISBN号码与之对应&#xff0c;ISBN码包括9位数字、1位识别码和3位分隔符&#xff0c;其规定格式如“x-xxx-xxxxx-x”&#xff0c;其中符号“-”就是分隔符&#xff08;键盘上的减号&#xff09;&#xff0c;最后一位是识别码&#xff0c;例如0…

scrapy爬虫启示录-小伙子老夫看你血气方刚这本《爬虫秘录》就传给你了

文章来源&#xff1a; IT源点 第一章 误入歧途 每个学习爬虫的人都有一颗爱美的心&#xff0c;俺也是一样的。那么多的美眉图片&#xff0c;不薅下来&#xff0c;没了谁负责。于是夜里孤枕难眠的老男孩开始了他的撸码之旅。从此在学习爬虫&#xff0c;学习Python的道路上越走…

自己设置假期的日历控件_在假期旅行时使用PC娱乐自己

自己设置假期的日历控件Staying connected may be hard no matter what network you are on, and in flight Wi-Fi isn’t pervasive enough to count on. Here are tips and tricks to keep yourself entertained when unplugged and traveling. 无论您使用什么网络&#xff0…

.Net CLR异常和windows C++ 异常调用栈简析

楔子前面一篇研究了下C异常的&#xff0c;这篇来看下&#xff0c;CLR的异常内存模型&#xff0c;实际上都是一个模型&#xff0c;承继自windows异常处理机制。不同的是&#xff0c;有VC编译器(vcruntime.dll&#xff09;接管的部分&#xff0c;被CLR里面的函数ProcessCLRExcept…