Spring boot mqtt客户端
- 导入依赖包
<dependency><groupId>org.eclipse.paho</groupId><artifactId>org.eclipse.paho.client.mqttv3</artifactId><version>1.2.0</version></dependency>
- 编写客户端连接配置类
package com.ha.mqtt.config.mqtt;import com.ha.common.core.utils.IdUtils; import org.eclipse.paho.client.mqttv3.*; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;@Configuration public class MqttClientConfig {@Value("${ha-config.mqtt.host}")private String host;@Value("${ha-config.mqtt.username}")private String username;@Value("${ha-config.mqtt.password}")private String password;@Value("${ha-config.mqtt.topic}")private String topic;private MqttClient client = null;private MqttAsyncClient mqttAsyncClient = null;@Beanpublic void initMqttClient() {try {String clientid = IdUtils.fastSimpleUUID();// MQTT的连接设置MqttConnectOptions options = new MqttConnectOptions();// 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录,这里设置为true表示每次连接到服务器都以新的身份连接options.setCleanSession(true);// 设置连接的用户名options.setUserName(username);// 设置连接的密码options.setPassword(password.toCharArray());// 设置超时时间 单位为秒options.setConnectionTimeout(10);// 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线,但这个方法并没有重连的机制options.setKeepAliveInterval(20);//是否自动重连options.setAutomaticReconnect(true);/*//同步阻塞式客户端// host为主机名,test为clientid即连接MQTT的客户端ID,一般以客户端唯一标识符表示,MemoryPersistence设置clientid的保存形式,默认为以内存保存client = new MqttClient(host, clientid, new MemoryPersistence());// 设置回调函数client.setCallback(new MqttPushClienCallback());client.connect(options);//订阅消息if (topic.contains(";")) {client.subscribe(topic.split(";"));} else {client.subscribe(topic);}*///异步非阻塞式客户端mqttAsyncClient = new MqttAsyncClient(host, clientid, new MemoryPersistence());mqttAsyncClient.setCallback(new MqttPushClienCallback());mqttAsyncClient.connect(options);if (topic.contains(";")) {String[] split = topic.split(";");int[] qos = new int[split.length];for (int i = 0; i < qos.length; ++i) {qos[i] = 1;}mqttAsyncClient.subscribe(split, qos);} else {mqttAsyncClient.subscribe(topic, 1);}} catch (Exception e) {e.printStackTrace();}}/*** 订阅主题** @param topic 主题*/public void subTopic(String topic) throws MqttException {subTopic(topic, 1);}/*** 订阅主题*/public void subTopic(String topic, int qos) throws MqttException {client.subscribe(topic, qos);}}
- 连接信息在配置文件
- 信息接收,异常重新类
package com.ha.mqtt.config.mqtt;import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; import org.eclipse.paho.client.mqttv3.MqttCallback; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;@Component public class MqttPushClienCallback implements MqttCallback {private static Logger logger = LoggerFactory.getLogger(MqttPushClienCallback.class);@Autowiredprivate MqttClientConfig mqttClientConfig;@Overridepublic void connectionLost(Throwable throwable) {try {logger.info("MQTT连接断开,发起重连......");logger.info("............正在连接............");mqttClientConfig.initMqttClient();//心跳主题mqttClientConfig.subTopic("mqtt/face/heartbeat");//其他主题mqttClientConfig.subTopic("mqtt/face/by_ing112233/Rec");mqttClientConfig.subTopic("mqtt/face/by_ing112233/Snap");mqttClientConfig.subTopic("mqtt/face/by_ing112233/Ack");} catch (MqttException e) {e.printStackTrace();}}/*** 接收mqttf服务信息*/@Overridepublic void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {System.out.println(".......接收到mqtt信息.......");logger.info("topid:{}", topic);logger.info("mqttMessage:{}", mqttMessage.getPayload());}@Overridepublic void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {} }
- 结果输出信息
Spring boot mqtt客户端相关推荐
- C++|Java混合实验-Spring Boot获取客户端操作系统,浏览器,Ip等信息,Qt端展示
目录 概述 演示 源码 概述 这里用Spring Boot控制"/"和"index.html"请求,获取客户端http的信息: Qt端使用QML和C++混合编程 ...
- spring boot websocket 客户端_Spring Boot 开发集成 WebSocket,实现私有即时通信系统
###1/ 概述 利用Spring Boot作为基础框架,Spring Security作为安全框架,WebSocket作为通信框架,实现点对点聊天和群聊天. ###2/ 所需依赖 Spring Bo ...
- Spring Boot Admin –用于管理Spring Boot应用程序的Admin UI
作为微服务开发的一部分,我们许多人都将Spring Boot与Spring Cloud功能一起使用. 在微服务领域,我们将有许多Spring Boot应用程序将在相同/不同的主机上运行. 如果将Spr ...
- SpringBoot实战(十四):Spring Boot Admin 集成安全模块
强烈推荐一个大神的人工智能的教程:http://www.captainbed.net/zhanghan [前言] Spring Boot Admin做为生产级的监控工具,必然不能随便让人去操作以免误操 ...
- 用Spring Boot Admin来监控我们的微服务
[转载请注明出处]:https://blog.csdn.net/huahao1989/article/details/108039738 1.概述 Spring Boot Admin是一个Web应用程 ...
- SpringCloud 微服务监控方案sentinel + spring boot admin
SpringCloud 微服务监控方案sentinel + spring boot admin 前言:项目基于springcloud框架,服务注册中心使用的是Eureka spring boot ad ...
- Springboot 系列(十七)迅速使用 Spring Boot Admin 监控你的 Spring Boot 程序
1. Spring Boot Admin 是什么 Spring Boot Admin 是由 codecentric 组织开发的开源项目,使用 Spring Boot Admin 可以管理和监控你的 S ...
- Springboot 系列(十七)迅速使用 Spring Boot Admin 监控你的 Spring Boot 程序,支持异常邮件通知
点赞再看,动力无限.Hello world : ) 微信搜「 程序猿阿朗 」. 本文 Github.com/niumoo/JavaNotes 和 未读代码博客 已经收录,有很多知识点和系列文章. 1. ...
- 第二章 Spring Boot四大核心组件
文章目录 前言 一.Spring Boot Starter 1.1 Starter的应用示例 1.2 Spring Boot之前的Thymeleaf和Mybatis应用 1.2.1 Thymeleaf ...
- 第8章Spring Boot整合监控
8.1 使用actuator监控 8.1.1 actuator是什么 在Spring Boot的众多Starter POMs中有一个特殊的模块,不同于其他模块大多用于开发业务功能或连接一些其他外部资源 ...
最新文章
- 【Whalepaper】NLP论文研读 - Keyword-Attentive Deep Semantic Matching
- 58 Node.js中操作mongoDB数据库
- 10条有益的涉世忠告
- matlab训练集测试集划分
- Authentication Error errorcode: 230 uid: -1 appid -1 msg: APP Scode码校验失败
- java 优化线程_JAVA线程优化
- yum搭建lnmp的最简单方法
- The Number of Products
- Maven本地环境配置(Win10)
- sd卡插入计算机要格式化,内存卡一直提示格式化,内存卡插电脑要格式化-
- SpringBoot请求第三方接口
- tf7: RNN—古诗词
- 如何打开计算机共享文件,如何打开共享文件 局域网文件共享的图文方法
- 计算机桌面的图标怎么删除,桌面图标有蓝底怎么去掉,教您去掉电脑桌面图标蓝底的方法...
- Flink DataStream Keyed和Non-Keyed窗口、WindowAssigner、窗口生命周期、窗口函数、迟到数据和窗口结果的处理
- 使用“#define _GNU_SOURCE” 是什么意思?
- 工作三年,回顾一下工作历程
- 漂白水增稠剂看似木讷,其实在专注于分析罢了
- 淘宝、百度、腾讯、京东 那不得不说的四角恋故事
- Pytorch+LSTM+Encoder+Decoder实现Seq2Seq模型