Working on IOT With Spring Boot Using MQTT
Posted By : Shivansh Pandey | 02-Sep-2020
In this blog, you'll learn about working on IoT with Spring Boot Using MQTT. MQTT is a light weight bi-directional publish-subscribe based protocol which is used to communicate with remote devices. This protocol is owned by an organization named 'OASIS'. MQTT is most popular in the automobile sector for tracking the battery health of vehicles,locations etc.
How Does MQTT Work?
As we know that for working on MQTT ,the first thing we need is to setup a MQTT Broker(on the server).
The broker acts as a mediator between our Spring boot application and the IOT devices.
So the first step is to install mqtt broker on ur Linux system.
Messeges are published on a topic by the clients and the MQTT broker just filters those messages on the basis of topic and distribute the messages to the subscribers of that topic.
MQTT Broker and MQTT Client
An MQTT broker is a server that receives messages from the clients and then routes those messages to the desired client destinations. An MQTT client is any device (from a micro controller up to a full-fledged server) that runs an MQTT library and connects to an MQTT broker over a network.(Spring boot application also acts as an MQTT Client).
The most popular mqtt brokers are -
Mosqitto
VerneMq
RabbitMq
EMQ.
Mqtt broker runs on 1883 port.
Spring Boot With MQTT
Step1- Create dependency
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.0</version>
</dependency>
Step2- Connect the broker
import org.eclipse.paho.client.mqttv3.IMqttClient;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
public class Mqtt {
private static final String MQTT_PUBLISHER_ID = "spring-server";
private static final String MQTT_SERVER_ADDRES= "tcp://127.0.0.1:1883";
private static IMqttClient instance;
public static IMqttClient getInstance() {
try {
if (instance == null) {
instance = new MqttClient(MQTT_SERVER_ADDRES, MQTT_PUBLISHER_ID);
}
MqttConnectOptions options = new MqttConnectOptions();
options.setAutomaticReconnect(true);
options.setCleanSession(true);
options.setConnectionTimeout(10);
if (!instance.isConnected()) {
instance.connect(options);
}
} catch (MqttException e) {
e.printStackTrace();
}
return instance;
}
private Mqtt() {
}
}
Step 3 - Start publishing and subscribing
For Publishing on MQTT Topic
public void publish(final String topic, final String payload, int qos, boolean retained)
throws MqttPersistenceException, MqttException {
MqttMessage mqttMessage = new MqttMessage();
mqttMessage.setPayload(payload.getBytes());
mqttMessage.setQos(qos);
mqttMessage.setRetained(retained);
Mqtt.getInstance().publish(messagePublishModel.getTopic(), mqttMessage);
mqttClient.disconnect();
}
For Subscribing MQTT Topic
public void subscribe(final String topic) throws MqttException, InterruptedException {
System.out.println("Messages received:");
Mqtt.getInstance().subscribeWithResponse(topic, (tpic, msg) -> {
System.out.println(msg.getId() + " -> " + new String(msg.getPayload()));
});
}
NOTE - There are many mqtt clients are available as MQTT.fx ,You can install them for your help.
Image credit - https://mqtt.org/
Explore our offerings in SaaS application development services. For more information, contact us at [email protected].
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Shivansh Pandey
He is a backend developer having good knowledge of java. He is having experience in Springboot, MQTT, Spring Cloud, etc. He writes optimized codes and having good problem-solving techniques.