首页
归档
留言
广告合作
友链
美女主播
Search
1
博瑞GE车机升级/降级
5,146 阅读
2
Mac打印机设置黑白打印
4,517 阅读
3
修改elementUI中el-table树形结构图标
4,516 阅读
4
Mac客户端添加腾讯企业邮箱方法
4,351 阅读
5
intelliJ Idea 2022.2.X破解
4,060 阅读
Java
HarmonyOS Next
Web前端
微信开发
开发辅助
App开发
数据库
随笔日记
登录
/
注册
Search
标签搜索
Spring Boot
Java
Spring Cloud
Mac
mybatis
WordPress
Nacos
Spring Cloud Alibaba
Mybatis-Plus
jQuery
Java Script
asp.net
微信小程序
Sentinel
UniApp
MySQL
asp.net core
IntelliJ IDEA
Jpa
树莓派
Laughing
累计撰写
570
篇文章
累计收到
1,424
条评论
首页
栏目
Java
HarmonyOS Next
Web前端
微信开发
开发辅助
App开发
数据库
随笔日记
页面
归档
留言
广告合作
友链
美女主播
搜索到
3
篇与
的结果
2021-05-17
MQTT使用三之Spring Boot集成MQTT简单使用
Spring Boot集成MQTT支持动态创建topic。添加依赖 <!-- MQTT --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-integration</artifactId> </dependency> <dependency> <groupId>org.springframework.integration</groupId> <artifactId>spring-integration-stream</artifactId> </dependency> <dependency> <groupId>org.springframework.integration</groupId> <artifactId>spring-integration-mqtt</artifactId> </dependency>添加配置文件server: port: 9999 #mqtt的配置 mqtt: server: url: tcp://ip:1883 port: 1883 username: 用户名 password: 密码 client: consumerId: consumerCo publishId: publishCo default: topic: topic completionTimeout: 3000MQTT配置文件package net.xiangcaowuyu.mqtt.config; import net.xiangcaowuyu.mqtt.utils.MqttReceiveHandle; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; 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.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.MessageHandler; import org.springframework.messaging.MessagingException; import org.springframework.util.StringUtils; import javax.annotation.Resource; import java.util.Arrays; import java.util.List; /** * Description:消息订阅配置 * * @author : laughing * DateTime: 2021-05-18 13:31 */ @Configuration public class MqttConfig { public final Logger logger = LoggerFactory.getLogger(this.getClass()); private static final byte[] WILL_DATA; static { WILL_DATA = "offline".getBytes(); } @Resource private MqttReceiveHandle mqttReceiveHandle; @Value("${mqtt.server.url}") private final String url = "tcp://139.198.172.114:1883"; @Value("${mqtt.server.port}") private final String port = "1883"; @Value("${mqtt.server.username}") private final String username = "admin"; @Value("${mqtt.server.password}") private final String password = "public"; @Value("${mqtt.client.consumerId}") private final String consumerId = "consumerClient"; @Value("${mqtt.client.publishId}") private final String publishId = "publishClient"; @Value("${mqtt.default.topic}") private final String topic = "topic"; @Value("${mqtt.default.completionTimeout}") private final Integer completionTimeout = 3000; //消息驱动 private MqttPahoMessageDrivenChannelAdapter adapter; //订阅的主题列表 private String listenTopics = ""; // //mqtt消息接收接口 // private MqttReceiveService mqttReceiveService; // // public void setMqttReceiveService(MqttReceiveService mqttReceiveService){ // this.mqttReceiveService = mqttReceiveService; // } /** * MQTT连接器选项 * **/ @Bean(value = "getMqttConnectOptions") public MqttConnectOptions getMqttConnectOptions(){ MqttConnectOptions mqttConnectOptions=new MqttConnectOptions(); // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录,这里设置为true表示每次连接到服务器都以新的身份连接 mqttConnectOptions.setCleanSession(true); // 设置超时时间 单位为秒 mqttConnectOptions.setConnectionTimeout(10); mqttConnectOptions.setAutomaticReconnect(true); mqttConnectOptions.setUserName(username); mqttConnectOptions.setPassword(password.toCharArray()); mqttConnectOptions.setServerURIs(new String[]{url}); // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送心跳判断客户端是否在线,但这个方法并没有重连的机制 mqttConnectOptions.setKeepAliveInterval(10); // 设置“遗嘱”消息的话题,若客户端与服务器之间的连接意外中断,服务器将发布客户端的“遗嘱”消息。 mqttConnectOptions.setWill("willTopic", WILL_DATA, 2, false); return mqttConnectOptions; } /** * MQTT工厂 * **/ @Bean public MqttPahoClientFactory mqttClientFactory() { DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory(); factory.setConnectionOptions(getMqttConnectOptions()); return factory; } /** * MQTT信息通道(生产者) * **/ @Bean public MessageChannel mqttOutboundChannel() { return new DirectChannel(); } /** * MQTT消息处理器(生产者) * **/ @Bean @ServiceActivator(inputChannel = "mqttOutboundChannel") public MessageHandler mqttOutbound() { MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(publishId, mqttClientFactory()); messageHandler.setAsync(true); messageHandler.setDefaultTopic(topic); return messageHandler; } /** * 配置client,监听的topic * MQTT消息订阅绑定(消费者) * **/ @Bean public MessageProducer inbound() { if(adapter == null){ adapter = new MqttPahoMessageDrivenChannelAdapter(consumerId, mqttClientFactory(), topic); } String [] topics = listenTopics.split(","); for(String topic: topics){ if(!StringUtils.isEmpty(topic)){ adapter.addTopic(topic,1); } } adapter.setCompletionTimeout(completionTimeout); adapter.setConverter(new DefaultPahoMessageConverter()); adapter.setQos(2); adapter.setOutputChannel(mqttInputChannel()); return adapter; } /** * 增加监听的topic * @param topicArr 消息列表 * @return 结果 */ public List<String> addListenTopic(String [] topicArr){ if(adapter == null){ adapter = new MqttPahoMessageDrivenChannelAdapter(consumerId, mqttClientFactory(), topic); } List<String> listTopic = Arrays.asList(adapter.getTopic()); for(String topic: topicArr){ if(!StringUtils.isEmpty(topic)){ if(!listTopic.contains(topic)){ adapter.addTopic(topic,1); } } } return Arrays.asList(adapter.getTopic()); } /** * 移除一个监听的topic * @param topic * @return */ public List<String> removeListenTopic(String topic){ if(adapter == null){ adapter = new MqttPahoMessageDrivenChannelAdapter(consumerId, mqttClientFactory(), topic); } List<String> listTopic = Arrays.asList(adapter.getTopic()); if(listTopic.contains(topic)){ adapter.removeTopic(topic); } return Arrays.asList(adapter.getTopic()); } /** * MQTT信息通道(消费者) * **/ @Bean public MessageChannel mqttInputChannel() { return new DirectChannel(); } /** * MQTT消息处理器(消费者) * **/ @Bean @ServiceActivator(inputChannel = "mqttInputChannel") public MessageHandler handler() { return new MessageHandler() { @Override public void handleMessage(Message<?> message) throws MessagingException { //处理接收消息 mqttReceiveHandle.handle(message); //String topic = message.getHeaders().get("mqtt_receivedTopic").toString(); //String msg = ((String) message.getPayload()).toString(); //mqttReceiveService.handlerMqttMessage(topic,msg); } }; } } 消息处理package net.xiangcaowuyu.mqtt.utils; import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; import org.eclipse.paho.client.mqttv3.MqttCallback; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.integration.mqtt.support.MqttHeaders; import org.springframework.messaging.Message; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.util.Date; @Component public class MqttReceiveHandle implements MqttCallback { private final Logger logger = LoggerFactory.getLogger(MqttReceiveHandle.class); public void handle(Message<?> message) { try { logger.info("{},客户端号:{},主题:{},QOS:{},消息接收到的数据:{}", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), message.getHeaders().get(MqttHeaders.ID), message.getHeaders().get(MqttHeaders.RECEIVED_TOPIC), message.getHeaders().get(MqttHeaders.RECEIVED_QOS), message.getPayload()); //处理mqtt数据 this.handle(message.getPayload().toString()); } catch (Exception e) { e.printStackTrace(); logger.error("处理错误" + e.getMessage()); } } private void handle(String str) throws Exception { logger.info(str); } @Override public void connectionLost(Throwable throwable) { logger.warn("连接丢失"); } @Override public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception { logger.info("消息到达:" + topic + "\n" + "消息内容:" + new String(mqttMessage.getPayload()) + "\nclientId:" + mqttMessage.getId()); } @Override public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) { logger.info("clientId:" + iMqttDeliveryToken.getClient().getClientId()); } }消息发送package net.xiangcaowuyu.mqtt.utils; import org.springframework.integration.annotation.MessagingGateway; import org.springframework.integration.mqtt.support.MqttHeaders; import org.springframework.messaging.handler.annotation.Header; /** * Description: * * @author : laughing * DateTime: 2021-05-18 13:44 */ @MessagingGateway(defaultRequestChannel = "mqttOutboundChannel") public interface MqttGateway { /** * 发送信息到MQTT服务器 * * @param data 发送的文本 */ void sendToMqtt(String data); /** * 发送信息到MQTT服务器 * * @param topic 主题 * @param payload 消息主体 */ void sendToMqtt(@Header(MqttHeaders.TOPIC) String topic, String payload); /** * 发送信息到MQTT服务器 * * @param topic 主题 * @param qos 对消息处理的几种机制。 * 0 表示的是订阅者没收到消息不会再次发送,消息会丢失。 * 1 表示的是会尝试重试,一直到接收到消息,但这种情况可能导致订阅者收到多次重复消息。 * 2 多了一次去重的动作,确保订阅者收到的消息有一次。 * @param payload 消息主体 */ void sendToMqtt(@Header(MqttHeaders.TOPIC) String topic, @Header(MqttHeaders.QOS) int qos, String payload); }测试package net.xiangcaowuyu.mqtt.controller; import net.xiangcaowuyu.mqtt.config.MqttConfig; import net.xiangcaowuyu.mqtt.utils.MqttGateway; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import java.util.List; @RestController public class MqttController { @Resource private MqttGateway mqttGateway; @Resource private MqttConfig mqttConfig; @GetMapping("/add/{topic}") public String addTopic(@PathVariable("topic") String topic) { String[] topics = {topic}; List<String> list = mqttConfig.addListenTopic(topics); return list.toString(); } @GetMapping("/pub") public String pubTopic() { String topic = "temperature1"; String msg = "client msg at: " + String.valueOf(System.currentTimeMillis()); mqttGateway.sendToMqtt(topic, 2, msg); return "OK"; } @GetMapping("/del/{topic}") public String delTopic(@PathVariable("topic") String topic) { List<String> list = mqttConfig.removeListenTopic(topic); return list.toString(); } }
2021年05月17日
1,345 阅读
2 评论
0 点赞
2021-05-17
MQTT使用二之EMQ X的安装及使用
EMQ X (Erlang/Enterprise/Elastic MQTT Broker) 是基于 Erlang/OTP 平台开发的开源物联网 MQTT 消息服务器。Erlang/OTP是出色的软实时 (Soft-Realtime)、低延时 (Low-Latency)、分布式 (Distributed)的语言平台。MQTT 是轻量的 (Lightweight)、发布订阅模式 (PubSub) 的物联网消息协议。EMQ X 设计目标是实现高可靠,并支持承载海量物联网终端的MQTT连接,支持在海量物联网设备间低延时消息路由:稳定承载大规模的 MQTT 客户端连接,单服务器节点支持50万到100万连接。分布式节点集群,快速低延时的消息路由,单集群支持1000万规模的路由。消息服务器内扩展,支持定制多种认证方式、高效存储消息到后端数据库。完整物联网协议支持,MQTT、MQTT-SN、CoAP、LwM2M、WebSocket 或私有协议支持。服务器支持EMQ X 目前支持的操作系统:CentOS 6CentOS 7CentOS 8OpenSUSE tumbleweedDebian 9Debian 10Ubuntu 16.04Ubuntu 18.04Ubuntu 20.04macOS 10.13macOS 10.14macOS 10.15Windows Server 2019[alt type="warning"]产品部署建议 Linux 服务器,不推荐 Windows 服务器。[/alt]Shell 脚本一键安装 (Linux)curl https://repos.emqx.io/install_emqx.sh | bash包管理器安装(CentOS)安装所需要的依赖包sudo yum install -y yum-utils device-mapper-persistent-data lvm2使用以下命令设置稳定存储库,以 CentOS 7 为例sudo yum-config-manager --add-repo https://repos.emqx.io/emqx-ce/redhat/centos/7/emqx-ce.repo安装最新版本的 EMQ X Brokersudo yum install emqx启动直接启动 EMQ X Brokeremqx startsystemctl 启动sudo systemctl start emqx查看状态emqx_ctl status停止 EMQ X Brokeremqx stop卸载sudo yum remove emqxDashboard安装完成后,通过ip:18083,打开出现界面代表安装成功。默认用户名是 admin,密码是 public更多安装方式可以参考:https://docs.emqx.cn/broker/v4.3/getting-started/install.html#
2021年05月17日
1,394 阅读
0 评论
1 点赞
2021-05-17
MQTT使用一之MQTT介绍
之前其实也没有用过MQTT,最近接触MQTT是因为有几个项目涉及传感器,在与传感器对接的过程中,通过MQTT完成数据的交互。简介MQTT(message queuing telemetry transport)是IBM开发的即时通讯协议,是一种发布/订阅极其轻量级的消息传输协议,专门为网络受限设备、低宽带以及高延迟和不可靠的网络而设计的。由于以上轻量级的特点,是实现智能家居的首选传输协议,相比于XMPP,更加轻量级而且占用宽带低。特点由于采用发布/订阅的消息模式,可以提供一对多的消息发布轻量级,网络开销小对负载内容会有屏蔽的消息传输有三种消息发布质量(Qos): qos=0:“至多一次”,这一级别会发生消息丢失或重复,消息发布依赖于TCP/IP网络 qos=1:“至少一次”,确保消息到达,但消息重复可能会发生 qos=2:“只有一次”,确保消息到达一次通知机制,异常中断时会通知双方原理MQTT协议有三种身份:发布者、代理、订阅者,发布者和订阅者都为客户端,代理为服务器,同时消息的发布者也可以是订阅者(为了节约内存和流量发布者和订阅者一般都会定义在一起)。MQTT传输的消息分为主题(Topic,可理解为消息的类型,订阅者订阅后,就会收到该主题的消息内容(payload))和负载(payload,可以理解为消息的内容)两部分。
2021年05月17日
1,092 阅读
0 评论
1 点赞