Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use MQTT in Springboot

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly shows you "how to use MQTT in Springboot", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "how to use MQTT in Springboot" this article.

Why choose MQTT?

The definition of MQTT is believed to be plausible by many people, and this article does not discuss anything high-end, but aims to use it in the most simple and intuitive way so that every colleague who has just come into contact with can be applied as quickly as possible.

Start by analyzing what you need to use MQTT:

Message server

Frequent interactions between different applications / devices

May involve one-to-many message delivery

Based on the three points listed above, we can probably understand that the most suitable scenario for MQTT is when messages are an important part of the system and participate in the key business logic of the system.

MQTT, activate!

Now that we have decided to use it, the first thing we need to study is how to make MQTT work properly. After all, it is not easy to add a dependency to maven.

Altogether, we need to do the following two things:

Download the EMQX message server as broker

Introducing dependencies into maven

Org.springframework.integration spring-integration-mqtt 5.3.2.RELEASE

After completing the above two steps, start the EMQX server and officially enter our MQTT journey.

Mode of use

Using MQTT code in Spring Boot, the author summarizes the following two ways:

Using the message channel concept of spring-integration

Using traditional Client client concepts

The first kind will produce a certain degree of mental burden, but after the author successfully matches (plagiarism + making wheels) automatic registration, it is much more convenient than the latter.

Before introducing the specific code, let's briefly sort out the most common concepts in use:

Topic: the main way to spread MQTT messages. We publish messages to topics, subscribe to topics, read messages from topics and do business logic processing. Topics are the channels of messages.

Producer: the sender of MQTT messages, who send messages to the subject

Consumers: recipients of MQTT messages who subscribe to the topics they need and get messages from them

Broker: message transponder, through which messages are carried. EMQX is our broker. In use, we do not need to care about its implementation.

In fact, the process of using MQTT is as follows: producers send messages to topics-> broker for message delivery-> consumers who subscribe to the topic get the messages and carry out the corresponding business logic.

Client mode

This model is basically the same as the traditional database link, Redis link, and friends with development experience can easily control it. What we need to consider is whether to create a corresponding factory, a singleton pattern, a prototype, or a pool?

We use singleton mode for this introduction.

Create a factory class

First of all, we create a factory (we don't admit that design patterns are poisoned)

Public class MqttFactory {private static MqttProperties configuration; private static MqttClient client; / * get client instance * singleton mode, return if it exists, initialize * / public static MqttClient getInstance () {if (client = = null) {init ();} return client if it does not exist } / * initialize client * / public static void init () {try {client = new MqttClient (configuration.getAddress (), "client-" + System.currentTimeMillis ()); / / MQTT configuration object MqttConnectOptions options = new MqttConnectOptions () / / set automatic reconnection. For other specific parameters, please see MqttConnectOptions options.setAutomaticReconnect (true); if (! client.isConnected ()) {client.connect (options) }} catch (MqttException e) {LOGGER.error (String.format ("MQTT: connection to message server [% s] failed", configuration.getAddress ());}

For the specific configuration of MQTT, please see MqttConnectOptions, which will not be explained here.

With a word of mouth, the document is always better than some blogs!

Create a tool class

Next, we create a MqttUtil for sending messages and subscribing topics

Public class MqttUtil {/ * send message * @ param topic topic * @ param data message content * / public static void send (String topic, Object data) {/ / get client instance MqttClient client = MqttFactory.getInstance (); ObjectMapper mapper = new ObjectMapper () Try {/ / convert message to json string String json = mapper.writeValueAsString (data); client.publish (topic, new MqttMessage (json.getBytes (StandardCharsets.UTF_8);} catch (JsonProcessingException e) {LOGGER.error (String.format ("MQTT: topic [% s] message conversion json failed", topic) } catch (MqttException e) {LOGGER.error (String.format ("MQTT: topic [% s] failed to send message", topic)) }} / * subscription topic * @ param topic topic * @ param listener message listener processor * / public static void subscribe (String topic, IMqttMessageListener listener) {MqttClient client = MqttFactory.getInstance (); try {client.subscribe (topic, listener) } catch (MqttException e) {LOGGER.error (String.format ("MQTT: subscription to topic [% s] failed", topic));}

I believe friends have noticed IMqttMessageListener. We just need to create a listener class and implement IMqttMessageListener interface to process messages. The code is as follows:

Public class MessageListener implements IMqttMessageListener {/ * processing messages * @ param topic topic * @ param mqttMessage messages * / @ Override public void messageArrived (String topic, MqttMessage mqttMessage) throws Exception {LOGGER.info (String.format ("MQTT: message from subscription topic [% s]", topic, new String (mqttMessage.getPayload () } public static void main (String [] args) {/ / subscribe to the topic test01, using MessageListener to process its message MqttUtil.subscribe ("test01", new MessageListener ());}}

Whether it's sending or subscribing, is it easy to understand?

When the comfortable thing is over, it brings endless torture and emptiness. Come on, let's challenge the second mode of mental burden.

Spring Integration

What is Spring Integration? I'm sorry. I don't know. I don't want to know.

Why use Spring Integration? Because it's really easy to maintain.

Most of the tutorials on the Internet are aimed at Spring Integration, which may be my first contact, and I am baffled by the stereotype, so I choose to give up them and choose the automatic configuration mode of the Great God, and on the basis of it, I make corresponding adjustments to the mental burden.

Remember the concept we discussed before? Theme / producer / consumer

In Spring Integration, we add some new concepts and fine-tune the previous ones:

Channel: a channel for message transmission and reception, through which each message is drilled in and out.

Client factory: used to create MQTT clients, similar to those in pattern 1

Message adapter: used to receive MQTT messages for transformation, but does not participate in business logic

Inbound channel: with a message adapter, a channel for messages to enter the platform

Outbound channel: the channel that matches the client factory and the platform for sending messages.

Theme: it's still the theme, it doesn't change

Producer: the guy with the outbound channel

Consumer: the guy who has access to the station.

If you can gradually understand the above definition, the process of this pattern can actually look like this:

Producer: create the outbound channel of the specified client factory-> send messages

Consumer: create an inbound channel for the specified message adapter-> receive messages-> enter message interceptor-> business logic

In fact, in the author's opinion, this is in line with the concept of Spring Boot, agreement is better than configuration.

The above is all the content of the article "how to use MQTT in Springboot". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report