SpringBoot整合MQTT实践开发


MQTT简介:

MQTT(Message Queuing Telemetry Transport,消息队列遥测传输协议),是一种基于发布/订阅(publish/subscribe)模式的轻量级协议,该协议构建于TCP/IP协议之上,MQTT最大优点在于,可以以极少的代码和有限的带宽,为连接远程设备提供实时可靠的消息服务(这是特点)。作为一种低开销、低带宽占用的即时通讯协议,使其在物联网、小型设备、移动应用等方面有较广泛的应用。

MQTT应用范围:

MQTT是一个基于客户端-服务器的消息发布/订阅传输协议。MQTT协议是轻量、简单、开放和易于实现的,这些特点使它适用范围非常广泛。在很多情况下,包括受限的环境中,如:机器与机器(M2M)通信和物联网(IoT)。其在,通过卫星链路通信传感器、偶尔拨号的医疗设备、智能家居、及一些小型化设备中已广泛使用。

分享给大家一套SpringBoot的视频教程,这套视频由浅入深,带你体验Spring Boot的极速开发过程,内容丰富,涵盖了SpringBoot开发的方方面面,并且同步更新到Spring Boot 2.x系列的最新版本,让你一次性拿下Spring Boot开发框架。

视频教程在线观看:

SpringBoot框架从入门到实践视频课程 - Spring Boot - 动力节点在线 (bjpowernode.com)

资料及源码免费下载:

SpringBoot学习视频_全套SpringBoot基础教程免费下载 - 动力节点 (bjpowernode.com)

引入maven依赖

1 <dependency>
2 <groupId>org.eclipse.paho</groupId>
3 <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
4 <version>1.2.0</version>
5 </dependency>
1、Mqtt
 1 @Component
 2 public class Mqtt implements CommandLineRunner {
 3 
 4 
 5 @Autowired
 6 private CommitUserInfo commitUserInfol;
 7 @Autowired
 8 private UserInfoDao userInfoDao; // 数据库CRUD接口
 9 @Autowired
10 private ApplicationRedis applicationRedis; // redis 接口
11 @Autowired
12 JudgeEquipmentService judgeEquipmentService; // 查询/修改---当前设备号码状态
13 
14 @Override
15 public void run(String... args) throws Exception {
16 applicationRedis.test();
17 MqttConnectionUtils.start(userInfoDao,applicationRedis,judgeEquipmentService,commitUserInfol);
18 
19 }
20 
21 
22 
23 }

2.MqttConnectionUtils

 1 private static MqttClient client;
 2 
 3 private static MqttConnectOptions connectOptions;
 4 
 5 private static String TOPIC;
 6 
 7 private static String clientId;
 8 
 9 private static final Logger LOG = LogManager.getLogger(MqttConnectionUtils.class);
10 static {
11 try {
12 clientId = UUID.randomUUID().toString().trim().replaceAll("-", "");
13 client = new MqttClient("tcp://****:1883",clientId);
14 connectOptions=new MqttConnectOptions();
15 connectOptions.setCleanSession(false);
16 connectOptions.setUserName("用户名");
17 connectOptions.setPassword(PropertiesReader.getPassword().toCharArray());//密码 connectOptions.setConnectionTimeout(10);
18 client.setTimeToWait(10000);
19 client.connect(connectOptions);
20 TOPIC = PropertiesReader.getTopic();
21 } catch (MqttException e) {
22 e.printStackTrace();
23 }
24 }
25 
26 
27 /**
28 * 发送数据
29 */
30 
31 public static void publish(String topic,String content) throws MqttException {
32 MqttMessage message=new MqttMessage(content.getBytes());
33 message.setQos(1);
34 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
35 LOG.info("发送时间========"+df.format(new Date()));
36 LOG.info(topic+"主题发送成功,内容:"+message);
37 client.publish(topic,message);
38 }
39 
40 /**
41 * 接收数据
42 */
43 
44 public static void start(UserInfoDao userInfoDao, ApplicationRedis applicationRedis,
45 JudgeEquipmentService judgeEquipmentService, CommitUserInfo commitUserInfol) throws MqttException {
46 MqttTopic topic = client.getTopic(TOPIC);
47 // setWill方法,如果项目中需要知道客户端是否掉线可以调用该方法。设置最终端口的通知消息
48 connectOptions.setWill(topic, "close".getBytes(), 2, true);
49 
50 // 订阅消息
51 int[] Qos = { 1 };
52 String[] topic1 = { TOPIC };
53 client.subscribe(topic1, Qos);
54 // 设置回调
55 client.setCallback(new PushCallback(userInfoDao,applicationRedis,judgeEquipmentService,commitUserInfol));
56 LOG.info("WIFI版启动成功=================");
57 }
58 
59 
60 /**
61 * mqtt重连
62 */
63 public static void reConnect() {
64 while (true){
65 try {
66 if (null != client && !(client.isConnected())) {
67 Thread.sleep(1000);
68 clientId = UUID.randomUUID().toString().trim().replaceAll("-", "");
69 client.connect(connectOptions);
70 LOG.info("=======尝试重新连接==============");
71 break;
72 }
73 } catch (MqttException | InterruptedException e) {
74 LOG.info("=======重新连接失败:{}==============", e.toString());
75 continue;
76 }
77 }
78 
79 }

3.PushCallback

 1 import com.alibaba.fastjson.JSONObject;
 2 
 3 import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
 4 import org.eclipse.paho.client.mqttv3.MqttCallback;
 5 import org.eclipse.paho.client.mqttv3.MqttException;
 6 import org.eclipse.paho.client.mqttv3.MqttMessage;
 7 import org.springframework.beans.factory.annotation.Autowired;
 8 
 9 import java.io.UnsupportedEncodingException;
10 import java.util.*;
11 
12 public class PushCallback implements MqttCallback{
13 
14 public static PushCallback pushCallback;
15 
16 @Autowired
17 private UserInfoDao userInfoDao; // 数据库CRUD接口
18 
19 @Autowired
20 private CommitUserInfo commitUserInfol;
21 
22 @Autowired
23 private ApplicationRedis applicationRedis; // redis 接口
24 @Autowired
25 JudgeEquipmentService judgeEquipmentService; // 查询/修改---当前设备号码状态
26 
27 
28 
29 public PushCallback(UserInfoDao userInfoDao,ApplicationRedis applicationRedis,
30 JudgeEquipmentService judgeEquipmentService, CommitUserInfo commitUserInfol){
31 this.userInfoDao = userInfoDao;
32 this.applicationRedis = applicationRedis;
33 this.judgeEquipmentService = judgeEquipmentService;
34 this.commitUserInfol = commitUserInfol;
35 }
36 @Override
37 public void connectionLost(Throwable throwable) {
38 // 连接丢失后,一般在这里面进行重连
39 System.out.println("WIFI版======连接断开,可以做重连");
40 MqttConnectionUtils.reConnect();
41 }
42 
43 @Override
44 public void messageArrived(String topic, MqttMessage message) throws Exception {
45 // subscribe后得到的消息会执行到这里面
46 String messages = new String(message.getPayload());
47 if(!messages.equals("close")){
48 System.out.println("接收消息主题 : " + topic);
49 System.out.println("接收消息Qos : " + message.getQos());
50 System.out.println("接收消息内容 : " + new String(message.getPayload()));
51 try {
52 
53 perform(topic,json);
54 
55 }catch (Exception e){
56 
57 }
58 
59 }
60 
61 
62 }
63 
64 @Override
65 public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
66 System.out.println("deliveryComplete---------" +iMqttDeliveryToken.isComplete());
67 }
68 
69 public void perform(String topicP,JSONObject json) throws MqttException, UnsupportedEncodingException {
70 //你的业务模块
71 }
72 
73 
74 }

 

 

 


 

转载自:CSDN作者JAVA叶知秋

原文链接:https://blog.csdn.net/qq_37996327/article/details/104797737

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM