java connection to MQTT server

1, Business scenario

The data collected by hardware is transferred to EMQX platform (using MQTT protocol), and java connects to MQTT server through code to receive, analyze, process, store and display the collected data.

MQTT is based on publish / subscribe mode for communication and data exchange.

2, This article only explains how to connect java to MQTT server for data processing

1. Create a new springboot project, and introduce the following mqtt dependency directly into the pom file

        <dependency>
            <groupId>org.springframework.integration</groupId>
            <artifactId>spring-integration-mqtt</artifactId>
        </dependency>

2. Writing MQTT tool class

package com.siborui.dc.mqtt;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * MQTT Tool class operation
 *
 * @author Mr.Qu
 * @since v1.1.0 2020-01-10
 */
@Slf4j
@Component
public class MQTTConnect {

    private String HOST = tcp://127.0.0.1:1883; / / address and port number of mqtt server
    private final String clientId = "DC" + (int) (Math.random() * 100000000);
    private MqttClient mqttClient;

    /**
     * Client connect to mqtt server
     *
     * @param userName     User name
     * @param passWord     Password
     * @param mqttCallback Callback function
     **/
    public void setMqttClient(String userName, String passWord, MqttCallback mqttCallback) throws MqttException {
        MqttConnectOptions options = mqttConnectOptions(userName, passWord);
        if (mqttCallback == null) {
            mqttClient.setCallback(new Callback());
        } else {
            mqttClient.setCallback(mqttCallback);
        }
        mqttClient.connect(options);
    }

    /**
     * MQTT Connection parameter settings
     */
    private MqttConnectOptions mqttConnectOptions(String userName, String passWord) throws MqttException {
        mqttClient = new MqttClient(HOST, clientId, new MemoryPersistence());
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName(userName);
        options.setPassword(passWord.toCharArray());
        options.setConnectionTimeout(10);/// default: 30
        options.setAutomaticReconnect(true);//Default: false
        options.setCleanSession(false);//Default: true
        //options.setKeepAliveInterval(20); / / default: 60
        return options;
    }

    /**
     * Close MQTT connection
     */
    public void close() throws MqttException {
        mqttClient.close();
        mqttClient.disconnect();
    }

    /**
     * Publish message to a subject default qos: 1
     *
     * @param topic:Published topics
     * @param msg: Published messages
     */
    public void pub(String topic, String msg) throws MqttException {
        MqttMessage mqttMessage = new MqttMessage();
        //mqttMessage.setQos(2);
        mqttMessage.setPayload(msg.getBytes());
        MqttTopic mqttTopic = mqttClient.getTopic(topic);
        MqttDeliveryToken token = mqttTopic.publish(mqttMessage);
        token.waitForCompletion();
    }

    /**
     * Publish a message to a topic
     *
     * @param topic: Published topics
     * @param msg:   Published messages
     * @param qos:   Message quality Qos: 0, 1, 2
     */
    public void pub(String topic, String msg, int qos) throws MqttException {
        MqttMessage mqttMessage = new MqttMessage();
        mqttMessage.setQos(qos);
        mqttMessage.setPayload(msg.getBytes());
        MqttTopic mqttTopic = mqttClient.getTopic(topic);
        MqttDeliveryToken token = mqttTopic.publish(mqttMessage);
        token.waitForCompletion();
    }

    /**
     * Subscribe to a topic. The default Qos level of this method is: 1
     *
     * @param topic theme
     */
    public void sub(String topic) throws MqttException {
        mqttClient.subscribe(topic);
    }

    /**
     * Subscribe to a topic, and you can carry Qos
     *
     * @param topic Topics to subscribe to
     * @param qos   Message quality: 0, 1, 2
     */
    public void sub(String topic, int qos) throws MqttException {
        mqttClient.subscribe(topic, qos);
    }

    /**
     * main Function self test
     */
    public static void main(String[] args) throws MqttException {
        MQTTConnect mqttConnect = new MQTTConnect();
        mqttConnect.setMqttClient("admin", "public", new Callback());
        mqttConnect.pub("com/dc/init", "Mr.Qu" + (int) (Math.random() * 100000000));
        mqttConnect.sub("com/iot/init");
    }
}

3. Writing callback function of MQTT

package com.siborui.dc.mqtt;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;

/**
 * MQTT Callback function
 *
 * @author Mr.Qu
 * @since 2020/1/9 16:26
 */
public class Callback implements MqttCallback {

    /**
     * MQTT Disconnection does this
     */
    @Override
    public void connectionLost(Throwable throwable) {

    }

    /**
     * subscribe The message after subscription will be executed here
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

    }
    
    /**
     * publish It will be implemented here after successful publishing
     */
    @Override
    public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
        //  TODO: Here you can process and store the subscribed messages
    }
}

4. Because of the needs of the business scenario, when the project is started, listen to the MQTT Topic and write an MQTT listener

package com.siborui.dc.mqtt;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import com.siborui.dc.mqtt.Callback;

/**
 * Project start listening topic
 *
 * @author Mr.Qu
 * @since 2020/1/10
 */
@Slf4j
@Component
public class MQTTListener implements ApplicationListener<ContextRefreshedEvent> {

    private final MQTTConnect server;

    @Autowired
    public MQTTListener(MQTTConnect server) {
        this.server = server;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        try {
            server.setMqttClient("admin", "public", new Callback());
            server.sub("com/iot/collection/");
        } catch (MqttException e) {
            log.error(e.getMessage(), e);
        }
    }
}


 

Published 1 original article, praised 0, visited 6
Private letter follow

Tags: Eclipse Java Lombok SpringBoot

Posted on Mon, 13 Jan 2020 11:48:59 -0500 by millsy007