Gateway绑定MQTT实现发布订阅
来源:SegmentFault
时间:2023-01-13 08:10:45 397浏览 收藏
数据库小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《Gateway绑定MQTT实现发布订阅》带大家来了解一下Gateway绑定MQTT实现发布订阅,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!
创建项目
创建父工程
打开
idea点击 File>New>Project 选择Spring Initializr >JDK版本>Next 并按下图创建项目
点击
next,开发者工具
Developer Tools我们勾选前两个,
Web我们勾选第一个,安全框架和SQL这里暂时不需要勾选,Messaging中间件,我们同样勾选第一个就好,Cloud组件我们也不用勾选。
依次点击
next
finish创建好项目
删除
src,
.gitignore,
HELP.md,
mvnw和
mvnw.cmd目录,本文采用Gateway绑定的方式,需要引入以下依赖:
org.springframework.integration 官网是这么介绍的
这里选择第一种方式。yml配置文件:
application-common.ymlwulongbo: mqtt: emqx: username: admin password: public #tcp://ip:port host-url: tcp://39.102.56.91:1883 client-id: wulongbo${random.value} default-topic: wulongbo_topic # default-topic: $SYS/brokers/+/clients/# timeout: 60 keep-alive: 60 # qos:{0:至多一次的传输 /1:至少分发一次,可重复 /2:只分发一次,不可重复} qos: 1 version: 4注:我自身的EMQX 是启用了Mysql认证登录的,并且关闭了匿名登录的哈,所以需要正确的用户名和密码springboot_emqx_publish
在该模块下新建如下package包
config类:
EmqxMqttConfig.javapackage com.baba.wlb.publish.config; /** * @Author wulongbo * @Date 2020/12/29 11:38 * @Version 1.0 */ import com.baba.wlb.share.common.Constants; import com.baba.wlb.share.properties.EmqxMqttProperties; import lombok.extern.slf4j.Slf4j; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.integration.annotation.IntegrationComponentScan; import org.springframework.integration.annotation.ServiceActivator; import org.springframework.integration.channel.DirectChannel; import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory; import org.springframework.integration.mqtt.core.MqttPahoClientFactory; import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.MessageHandler; import javax.annotation.Resource; /** * EMQX配置工具类 */ @Configuration @IntegrationComponentScan //消息扫描件 @Slf4j public class EmqxMqttConfig { @Resource private EmqxMqttProperties emqxMqttProperties; /** * MQTT的连接 */ @Bean public MqttConnectOptions getMqttConnectOptions() { // 设置相关的属性 MqttConnectOptions mqttConnectOptions = new MqttConnectOptions(); mqttConnectOptions.setUserName(emqxMqttProperties.getUsername()); mqttConnectOptions.setPassword(emqxMqttProperties.getPassword().toCharArray()); mqttConnectOptions.setServerURIs(new String[]{emqxMqttProperties.getHostUrl()}); // 心跳 mqttConnectOptions.setKeepAliveInterval(emqxMqttProperties.getKeepAlive()); mqttConnectOptions.setMqttVersion(emqxMqttProperties.getVersion()); mqttConnectOptions.setConnectionTimeout(emqxMqttProperties.getTimeout()); // 保留/清空曾经连接的客户端信息 mqttConnectOptions.setCleanSession(false); // qos String playload = "设备已断开连接"; // 遗嘱消息 mqttConnectOptions.setWill("last_topic", playload.getBytes(), emqxMqttProperties.getQos(), false); return mqttConnectOptions; } /** * paho factory,mqtt自定义的连接放入factory工厂中 */ @Bean public MqttPahoClientFactory getMqttPahoClientFactory() { DefaultMqttPahoClientFactory defaultMqttPahoClientFactory = new DefaultMqttPahoClientFactory(); defaultMqttPahoClientFactory.setConnectionOptions(getMqttConnectOptions()); return defaultMqttPahoClientFactory; } /** * 开启连接通道 */ @Bean(name = Constants.MQTT_PUBLISH_CHANNEL) public MessageChannel getMqttPublishMessageChannel() { DirectChannel directChannel = new DirectChannel(); return directChannel; } // /** // * 开启连接通道 // */ // @Bean(name = Constants.MQTT_SUBSCRIBE_CHANNEL) // public MessageChannel getMqttSubscribeMessageChannel() { // DirectChannel directChannel = new DirectChannel(); // return directChannel; // } // // // // /** // * 监听topic.订阅者,消费者 // */ // @Bean // public MessageProducer inbound() { // MqttPahoMessageDrivenChannelAdapter mqttPahoMessageDrivenChannelAdapter = new MqttPahoMessageDrivenChannelAdapter( // emqxMqttProperties.getClientId() + "_wlb", getMqttPahoClientFactory(), emqxMqttProperties.getDefaultTopic().split(",") // ); // mqttPahoMessageDrivenChannelAdapter.setDisconnectCompletionTimeout(emqxMqttProperties.getTimeout()); // mqttPahoMessageDrivenChannelAdapter.setConverter(new DefaultPahoMessageConverter()); // mqttPahoMessageDrivenChannelAdapter.setQos(emqxMqttProperties.getQos()); // mqttPahoMessageDrivenChannelAdapter.setOutputChannel(getMqttPublishMessageChannel()); // return mqttPahoMessageDrivenChannelAdapter; // } /** * 订阅者,消费者 */ @Bean @ServiceActivator(inputChannel = Constants.MQTT_PUBLISH_CHANNEL) public MessageHandler getMessageHandler() { MqttPahoMessageHandler mqttPahoMessageHandler = new MqttPahoMessageHandler(emqxMqttProperties.getClientId(),getMqttPahoClientFactory()); mqttPahoMessageHandler.setAsync(true); mqttPahoMessageHandler.setDefaultQos(emqxMqttProperties.getQos()); mqttPahoMessageHandler.setDefaultTopic(emqxMqttProperties.getDefaultTopic()); return mqttPahoMessageHandler; } }controller类:
PublishController.javapackage com.baba.wlb.publish.controller; import com.baba.wlb.publish.service.PublishService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @Author wulongbo * @Date 2020/12/29 13:58 * @Version 1.0 */ /** * 发送消息的Controller */ @RestController @RequestMapping("/publish") public class PublishController { /** * 注入发布者的service服务 */ @Autowired private PublishService publishService; /** * 发送消息 */ @RequestMapping("/emqxPublish") public String emqxPublish(String data,String topic){ publishService.sendToMqtt(data,topic); return "success"; } }service:
PublishService.javapackage com.baba.wlb.publish.service; import com.baba.wlb.share.common.Constants; import org.springframework.integration.annotation.MessagingGateway; import org.springframework.integration.mqtt.support.MqttHeaders; import org.springframework.messaging.handler.annotation.Header; import org.springframework.stereotype.Component; /** * @Author wulongbo * @Date 2020/12/29 14:00 * @Version 1.0 */ @MessagingGateway(defaultRequestChannel = Constants.MQTT_PUBLISH_CHANNEL) @Component public interface PublishService { void sendToMqtt(String data, @Header(MqttHeaders.TOPIC) String topic); void sendToMqtt(String data); void sendToMqtt(@Header(MqttHeaders.TOPIC)String topic, int qos, String data); }注:必须加@Header(MqttHeaders.TOPIC)注解哈application启动类:
PublishApplication.javapackage com.baba.wlb.publish; import com.baba.wlb.share.properties.EmqxMqttProperties; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; /** * @Author wulongbo * @Date 2020/12/29 14:04 * @Version 1.0 */ /** * emqx 发布者启动程序 */ @SpringBootApplication @EnableConfigurationProperties({EmqxMqttProperties.class}) public class PublishApplication { public static void main(String[] args) { SpringApplication.run(PublishApplication.class,args); } }注:须加入@EnableConfigurationProperties,才能加载到配置文件yml文件:
application.ymlserver: port: 1001 #spring: # profiles: # active: common注:这里我们因为把publish模块设置成为了主类,所以可引入common yml,也可以不引入springboot_emqx_subscribe
在该模块下新建如下package包
config类:
EmqxMqttConfig.javapackage com.baba.wlb.subscribe.config; /** * @Author wulongbo * @Date 2020/12/29 11:38 * @Version 1.0 */ import com.baba.wlb.share.common.Constants; import com.baba.wlb.share.properties.EmqxMqttProperties; import lombok.extern.slf4j.Slf4j; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.integration.annotation.IntegrationComponentScan; import org.springframework.integration.annotation.ServiceActivator; import org.springframework.integration.channel.DirectChannel; import org.springframework.integration.core.MessageProducer; import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory; import org.springframework.integration.mqtt.core.MqttPahoClientFactory; import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter; import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler; import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.MessageHandler; import javax.annotation.Resource; /** * EMQX配置工具类 */ @Configuration @IntegrationComponentScan //消息扫描件 @Slf4j public class EmqxMqttConfig { @Resource private EmqxMqttProperties emqxMqttProperties; /** * MQTT的连接 */ @Bean public MqttConnectOptions getMqttConnectOptions() { // 设置相关的属性 MqttConnectOptions mqttConnectOptions = new MqttConnectOptions(); mqttConnectOptions.setUserName(emqxMqttProperties.getUsername()); mqttConnectOptions.setPassword(emqxMqttProperties.getPassword().toCharArray()); mqttConnectOptions.setServerURIs(new String[]{emqxMqttProperties.getHostUrl()}); // 心跳 mqttConnectOptions.setKeepAliveInterval(emqxMqttProperties.getKeepAlive()); mqttConnectOptions.setMqttVersion(emqxMqttProperties.getVersion()); mqttConnectOptions.setConnectionTimeout(emqxMqttProperties.getTimeout()); // 保留/清空曾经连接的客户端信息 mqttConnectOptions.setCleanSession(false); // qos String playload = "设备已断开连接"; // 遗嘱消息 mqttConnectOptions.setWill("last_topic", playload.getBytes(), emqxMqttProperties.getQos(), false); return mqttConnectOptions; } /** * paho factory,mqtt自定义的连接放入factory工厂中 */ @Bean public MqttPahoClientFactory getMqttPahoClientFactory() { DefaultMqttPahoClientFactory defaultMqttPahoClientFactory = new DefaultMqttPahoClientFactory(); defaultMqttPahoClientFactory.setConnectionOptions(getMqttConnectOptions()); return defaultMqttPahoClientFactory; } // /** // * 开启连接通道 // */ // @Bean(name = Constants.MQTT_PUBLISH_CHANNEL) // public MessageChannel getMqttPublishMessageChannel() { // DirectChannel directChannel = new DirectChannel(); // return directChannel; // } /** * 开启连接通道 */ @Bean(name = Constants.MQTT_SUBSCRIBE_CHANNEL) public MessageChannel getMqttSubscribeMessageChannel() { DirectChannel directChannel = new DirectChannel(); return directChannel; } /** * 监听topic.订阅者,消费者 */ @Bean public MessageProducer inbound() { MqttPahoMessageDrivenChannelAdapter mqttPahoMessageDrivenChannelAdapter = new MqttPahoMessageDrivenChannelAdapter( emqxMqttProperties.getClientId() + "_wlb", getMqttPahoClientFactory(), emqxMqttProperties.getDefaultTopic().split(",") ); mqttPahoMessageDrivenChannelAdapter.setDisconnectCompletionTimeout(emqxMqttProperties.getTimeout()); mqttPahoMessageDrivenChannelAdapter.setConverter(new DefaultPahoMessageConverter()); mqttPahoMessageDrivenChannelAdapter.setQos(emqxMqttProperties.getQos()); mqttPahoMessageDrivenChannelAdapter.setOutputChannel(getMqttSubscribeMessageChannel()); return mqttPahoMessageDrivenChannelAdapter; } /** * 发布者,生产者 */ @Bean @ServiceActivator(inputChannel = Constants.MQTT_SUBSCRIBE_CHANNEL) public MessageHandler getMessageHandler() { MqttPahoMessageHandler mqttPahoMessageHandler = new MqttPahoMessageHandler(emqxMqttProperties.getClientId(),getMqttPahoClientFactory()); mqttPahoMessageHandler.setAsync(true); mqttPahoMessageHandler.setDefaultQos(emqxMqttProperties.getQos()); mqttPahoMessageHandler.setDefaultTopic(emqxMqttProperties.getDefaultTopic()); return mqttPahoMessageHandler; } }service业务类:
SubscribeService.javapackage com.baba.wlb.subscribe.service; import com.baba.wlb.share.common.Constants; import org.springframework.context.annotation.Bean; import org.springframework.integration.annotation.ServiceActivator; import org.springframework.messaging.Message; import org.springframework.messaging.MessageHandler; import org.springframework.messaging.MessagingException; import org.springframework.stereotype.Service; /** * @Author wulongbo * @Date 2020/12/29 14:11 * @Version 1.0 */ /** * 订阅者 */ @Service public class SubscribeService { @Bean @ServiceActivator(inputChannel = Constants.MQTT_SUBSCRIBE_CHANNEL) public MessageHandler messageHandler() { MessageHandler messageHandler = new MessageHandler() { @Override public void handleMessage(Message> message) throws MessagingException { System.out.println("订阅者订阅消息头是:" + message.getHeaders()); System.out.println("订阅者订阅消息主体是:" + message.getPayload()); } }; return messageHandler; } }注:我们把MessageHandler放入了专门的server做业务处理,其实放config类也是OK的application启动类:
SubscribeApplication.javapackage com.baba.wlb.subscribe; /** * @Author wulongbo * @Date 2020/12/29 14:16 * @Version 1.0 */ import com.baba.wlb.share.properties.EmqxMqttProperties; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; /** * 订阅者启动类 */ @SpringBootApplication @EnableConfigurationProperties({EmqxMqttProperties.class}) public class SubscribeApplication { public static void main(String[] args) { SpringApplication.run(SubscribeApplication.class,args); } }yml配置文件:
application.ymlserver: port: 1002 spring: profiles: include: common注:当然我们上面的publish和subscribe模块都是依赖于common模块的我们需要在各个模块上右击--Open Model Settings
并按下图依次来添加模块之间的依赖关系
最后,我们在分别在 publish和subscribe模块的pom文件中引入common依赖就Ok了com.baba.wlb springboot_emqx_common 1.0-SNAPSHOT
至此,我们多模块用Gateway绑定的方式就集成好了MQTT消息推送和消息订阅功能。启动项目
分别启动
PublishApplication和SubscribeApplication
端口分别为:1001,1002PostMan测试
打开postman:发起Get请求
localhost:1001/publish/emqxPublish?topic=wulongbo_topic&data=我是一条消息
可以看到我们订阅者订阅到了这条消息:至于service业务模块对消息的处理:具体是根据主题来筛选,还是根据playload来区分,看具体的业务场景和设计需要。当然EMQX 有更解耦的方式就是规则引擎来对各个事件响应动作,也有
HTTP API供我们调用,读者灵活运用即可。理论要掌握,实操不能落!以上关于《Gateway绑定MQTT实现发布订阅》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!
声明:本文转载于:SegmentFault 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
-
499 收藏
-
244 收藏
-
235 收藏
-
157 收藏
-
101 收藏
最新阅读
更多>
-
489 收藏
-
209 收藏
-
497 收藏
-
335 收藏
-
467 收藏
-
303 收藏
课程推荐
更多>
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 507次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 484次学习