SpringBoot項(xiàng)目接入MQTT的詳細(xì)指南
一、引言
MQTT(Message Queuing Telemetry Transport)是一種輕量級(jí)的消息傳輸協(xié)議,特別適用于物聯(lián)網(wǎng)(IoT)場(chǎng)景,具有低帶寬、高延遲網(wǎng)絡(luò)環(huán)境下的優(yōu)勢(shì)。Spring Boot 作為流行的 Java 開發(fā)框架,能夠方便地與 MQTT 集成,實(shí)現(xiàn)高效的消息通信。本文將詳細(xì)介紹如何在 Spring Boot 項(xiàng)目中接入 MQTT。
二、環(huán)境準(zhǔn)備
開發(fā)環(huán)境
- JDK 1.8 及以上版本
- Maven 3.x 或 Gradle
- Spring Boot 2.x 及以上版本
MQTT 服務(wù)器 可以選擇使用公共的 MQTT 服務(wù)器,如 HiveMQ 公共服務(wù)器(
tcp://broker.hivemq.com:1883),也可以自行搭建 Mosquitto 等 MQTT 服務(wù)器。
三、創(chuàng)建 Spring Boot 項(xiàng)目
可以使用 Spring Initializr(start.spring.io/)快速創(chuàng)建一個(gè) Spring Boot 項(xiàng)目,添加以下依賴:
- Spring Web
- Spring for Apache Pulsar(因?yàn)?Pulsar 也支持 MQTT 協(xié)議,同時(shí)這里我們會(huì)使用其相關(guān)的 MQTT 依賴)
如果使用 Maven,pom.xml 中添加如下依賴:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-mqtt</artifactId>
</dependency>
</dependencies>
解釋
url:MQTT 服務(wù)器的地址和端口。client-id:客戶端的唯一標(biāo)識(shí)。default-topic:默認(rèn)訂閱的主題。username和password:如果 MQTT 服務(wù)器需要認(rèn)證,則填寫相應(yīng)的用戶名和密碼。
五、創(chuàng)建 MQTT 配置類
創(chuàng)建一個(gè)配置類來配置 MQTT 連接和消息處理。
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
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.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;
@Configuration
public class MqttConfig {
@Bean
public MqttPahoClientFactory mqttClientFactory() {
DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
MqttConnectOptions options = new MqttConnectOptions();
options.setServerURIs(new String[]{"${spring.mqtt.url}"});
options.setUserName("${spring.mqtt.username}");
options.setPassword("${spring.mqtt.password}".toCharArray());
factory.setConnectionOptions(options);
return factory;
}
@Bean
public MessageChannel mqttInputChannel() {
return new DirectChannel();
}
@Bean
public MqttPahoMessageDrivenChannelAdapter inbound() {
MqttPahoMessageDrivenChannelAdapter adapter =
new MqttPahoMessageDrivenChannelAdapter("${spring.mqtt.client-id}", mqttClientFactory(),
"${spring.mqtt.default-topic}");
adapter.setCompletionTimeout(5000);
adapter.setConverter(new DefaultPahoMessageConverter());
adapter.setQos(1);
adapter.setOutputChannel(mqttInputChannel());
return adapter;
}
@Bean
@ServiceActivator(inputChannel = "mqttInputChannel")
public MessageHandler handler() {
return message -> {
System.out.println("Received message: " + message.getPayload());
};
}
@Bean
public MessageChannel mqttOutputChannel() {
return new DirectChannel();
}
@Bean
@ServiceActivator(inputChannel = "mqttOutputChannel")
public MessageHandler mqttOutbound() {
MqttPahoMessageHandler messageHandler =
new MqttPahoMessageHandler("${spring.mqtt.client-id}-publisher", mqttClientFactory());
messageHandler.setAsync(true);
messageHandler.setDefaultTopic("${spring.mqtt.default-topic}");
return messageHandler;
}
}
解釋
mqttClientFactory:創(chuàng)建 MQTT 客戶端工廠,配置連接選項(xiàng)。mqttInputChannel和mqttOutputChannel:定義消息通道,用于接收和發(fā)送消息。inbound:創(chuàng)建 MQTT 消息驅(qū)動(dòng)的通道適配器,用于訂閱主題并接收消息。handler:處理接收到的 MQTT 消息。mqttOutbound:創(chuàng)建 MQTT 消息處理程序,用于發(fā)布消息。
六、發(fā)送和接收 MQTT 消息
發(fā)送消息
創(chuàng)建一個(gè)服務(wù)類來發(fā)送 MQTT 消息。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.stereotype.Service;
@Service
public class MqttMessageSender {
@Autowired
private MessageChannel mqttOutputChannel;
public void sendMessage(String message) {
mqttOutputChannel.send(new GenericMessage<>(message));
}
}
接收消息
在配置類中已經(jīng)定義了消息處理邏輯,當(dāng)接收到消息時(shí),會(huì)在 handler 方法中進(jìn)行處理。
七、測(cè)試 MQTT 連接
創(chuàng)建一個(gè)控制器來測(cè)試 MQTT 消息的發(fā)送。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MqttController {
@Autowired
private MqttMessageSender mqttMessageSender;
@GetMapping("/send")
public String sendMessage(@RequestParam String message) {
mqttMessageSender.sendMessage(message);
return "Message sent: " + message;
}
}
啟動(dòng) Spring Boot 應(yīng)用程序,訪問 http://localhost:8080/send?message=Hello, MQTT! 即可發(fā)送 MQTT 消息。
八、總結(jié)
通過以上步驟,我們成功地在 Spring Boot 項(xiàng)目中接入了 MQTT,實(shí)現(xiàn)了消息的發(fā)送和接收。MQTT 作為一種輕量級(jí)的消息傳輸協(xié)議,與 Spring Boot 的集成可以幫助我們快速構(gòu)建高效、穩(wěn)定的物聯(lián)網(wǎng)消息通信系統(tǒng)。在實(shí)際應(yīng)用中,可以根據(jù)需求進(jìn)一步擴(kuò)展和優(yōu)化,如增加消息持久化、多主題訂閱等功能。
以上就是SpringBoot項(xiàng)目接入MQTT的詳細(xì)指南的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot接入MQTT的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Java后端實(shí)現(xiàn)異步編程的9種方式總結(jié)
我們?nèi)粘i_發(fā)的時(shí)候,經(jīng)常說到異步編程,比如說,在注冊(cè)接口,我們?cè)谟脩糇?cè)成功時(shí),用異步發(fā)送郵件通知用戶,那么實(shí)現(xiàn)異步編程一共有多少種方式呢,下面小編就來簡單講講吧2025-03-03
在Java中動(dòng)態(tài)執(zhí)行字符串代碼的方法小結(jié)
在Java編程中,靜態(tài)編譯的特性通常不允許我們直接執(zhí)行運(yùn)行時(shí)生成的代碼,然而,有時(shí)我們需要?jiǎng)討B(tài)地生成并執(zhí)行代碼片段,本文將詳細(xì)介紹如何在Java中運(yùn)行一段字符串代碼,并提供詳細(xì)的代碼案例和運(yùn)行結(jié)果,需要的朋友可以參考下2024-08-08
JavaScript中HTML元素操作的實(shí)現(xiàn)
本文主要介紹了JavaScript中HTML元素操作的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06
spring-cloud入門之spring-cloud-config(配置中心)
這篇文章主要介紹了spring-cloud入門之spring-cloud-config(配置中心),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-01-01
Java狀態(tài)機(jī)的一種優(yōu)雅寫法分享
狀態(tài)機(jī)是一種數(shù)學(xué)模型,對(duì)于我們業(yè)務(wù)實(shí)現(xiàn)有很大的幫助。我們可以用非常多的方法實(shí)現(xiàn)狀態(tài)機(jī),這篇文章就來介紹一個(gè)狀態(tài)機(jī)優(yōu)雅的實(shí)現(xiàn)方法,希望對(duì)大家有所幫助2023-04-04
如何在Spring?Boot微服務(wù)使用ValueOperations操作Redis集群String字符串
這篇文章主要介紹了在Spring?Boot微服務(wù)使用ValueOperations操作Redis集群String字符串類型數(shù)據(jù),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-06-06

