1. Introduction
MQTT (Message Queuing Telemetry Transport) is a lightweight message transmission protocol, especially suitable for Internet of Things (IoT) scenarios, with the advantages of low bandwidth and high latency network environments. As a popular Java development framework, Spring Boot can easily integrate with MQTT to achieve efficient message communication. This article will explain in detail how to access MQTT in Spring Boot projects.
2. Environmental preparation
-
Development Environment
- JDK 1.8 and above
- Maven or Gradle
- Spring Boot and above
MQTT ServerYou can choose to use a public MQTT server, such as HiveMQ public server (
tcp://:1883
), or you can also build MQTT servers such as Mosquitto.
3. Create Spring Boot Project
Spring Initializr can be used (/) Quickly create a Spring Boot project and add the following dependencies:
- Spring Web
- Spring for Apache Pulsar (because Pulsar also supports the MQTT protocol, and here we will use its related MQTT dependencies)
If using Maven,Add the following dependencies:
<dependencies> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId></groupId> <artifactId>spring-integration-mqtt</artifactId> </dependency> </dependencies>
explain
-
url
: The address and port of the MQTT server. -
client-id
: The unique identity of the client. -
default-topic
: The theme to subscribe to by default. -
username
andpassword
: If the MQTT server requires authentication, fill in the corresponding username and password.
5. Create an MQTT configuration class
Create a configuration class to configure MQTT connections and message processing.
import .; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; @Configuration public class MqttConfig { @Bean public MqttPahoClientFactory mqttClientFactory() { DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory(); MqttConnectOptions options = new MqttConnectOptions(); (new String[]{"${}"}); ("${}"); ("${}".toCharArray()); (options); return factory; } @Bean public MessageChannel mqttInputChannel() { return new DirectChannel(); } @Bean public MqttPahoMessageDrivenChannelAdapter inbound() { MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter("${-id}", mqttClientFactory(), "${-topic}"); (5000); (new DefaultPahoMessageConverter()); (1); (mqttInputChannel()); return adapter; } @Bean @ServiceActivator(inputChannel = "mqttInputChannel") public MessageHandler handler() { return message -> { ("Received message: " + ()); }; } @Bean public MessageChannel mqttOutputChannel() { return new DirectChannel(); } @Bean @ServiceActivator(inputChannel = "mqttOutputChannel") public MessageHandler mqttOutbound() { MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler("${-id}-publisher", mqttClientFactory()); (true); ("${-topic}"); return messageHandler; } }
explain
-
mqttClientFactory
: Create an MQTT client factory and configure connection options. -
mqttInputChannel
andmqttOutputChannel
: Define message channels for receiving and sending messages. -
inbound
: Create an MQTT message-driven channel adapter to subscribe to topics and receive messages. -
handler
: Process the received MQTT message. -
mqttOutbound
: Create an MQTT message handler to publish messages.
6. Send and receive MQTT messages
Send a message
Create a service class to send an MQTT message.
import ; import ; import ; import ; @Service public class MqttMessageSender { @Autowired private MessageChannel mqttOutputChannel; public void sendMessage(String message) { (new GenericMessage<>(message)); } }
Receive message
Message processing logic has been defined in the configuration class. When a message is received, it will behandler
Processing in the method.
7. Test MQTT connection
Create a controller to test the sending of MQTT messages.
import ; import ; import ; import ; @RestController public class MqttController { @Autowired private MqttMessageSender mqttMessageSender; @GetMapping("/send") public String sendMessage(@RequestParam String message) { (message); return "Message sent: " + message; } }
Start the Spring Boot application and accesshttp://localhost:8080/send?message=Hello, MQTT!
You can send an MQTT message.
8. Summary
Through the above steps, we successfully connected MQTT to the Spring Boot project, realizing the sending and receiving of messages. As a lightweight message transmission protocol, MQTT integration with Spring Boot can help us quickly build an efficient and stable IoT messaging system. In actual applications, it can be further expanded and optimized according to needs, such as adding functions such as message persistence, multi-theme subscription, etc.
The above is the detailed guide for accessing MQTT in SpringBoot project. For more information about accessing MQTT in SpringBoot, please follow my other related articles!