‘liusuyi’
2023-08-22 872ba4884f9929c9df6ebea52130bb27c1dd9fe8
src/main/java/com/ard/utils/mqtt/MqttConsumer.java
@@ -1,12 +1,17 @@
package com.ard.utils.mqtt;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.expression.spel.ast.NullLiteral;
import org.springframework.stereotype.Component;
import java.io.UnsupportedEncodingException;
/**
 * @Description: mqtt消费客户端
 * @ClassName: MqttConsumer
@@ -16,15 +21,15 @@
 **/
@Component
@Slf4j(topic = "mqtt")
@Order(1)
public class MqttConsumer implements ApplicationRunner {
    private static MqttClient client;
    @Override
    public void run(ApplicationArguments args) {
        log.info("初始化并启动mqtt......");
        if(PropertiesUtil.MQTT_ENABLED)
        {
        log.debug("初始化并启动mqtt......");
        if (PropertiesUtil.MQTT_ENABLED) {
            this.connect();
        }
    }
@@ -49,21 +54,21 @@
    }
    /**
     *  创建客户端  --- 1 ---
     * 创建客户端  --- 1 ---
     */
    public void getClient() {
        try {
            if (null == client) {
                client = new MqttClient(PropertiesUtil.MQTT_HOST, PropertiesUtil.MQTT_CLIENT_ID, new MemoryPersistence());
            }
            log.info("--创建mqtt客户端");
            log.debug("--创建mqtt客户端");
        } catch (Exception e) {
            log.error("创建mqtt客户端异常:" + e);
        }
    }
    /**
     *  生成配置对象,用户名,密码等  --- 2 ---
     * 生成配置对象,用户名,密码等  --- 2 ---
     */
    public MqttConnectOptions getOptions() {
        MqttConnectOptions options = new MqttConnectOptions();
@@ -76,12 +81,12 @@
        options.setKeepAliveInterval(PropertiesUtil.MQTT_KEEP_ALIVE);
        // 是否清除session
        options.setCleanSession(true);
        log.info("--生成mqtt配置对象");
        log.debug("--生成mqtt配置对象");
        return options;
    }
    /**
     *  qos   --- 3 ---
     * qos   --- 3 ---
     */
    public int[] getQos(int length) {
@@ -96,17 +101,17 @@
             */
            qos[i] = 1;
        }
        log.info("--设置消息发布质量");
        log.debug("--设置消息发布质量");
        return qos;
    }
    /**
     *  装载各种实例和订阅主题  --- 4 ---
     * 装载各种实例和订阅主题  --- 4 ---
     */
    public void create(MqttConnectOptions options, String[] topic, int[] qos) {
        try {
            client.setCallback(new MqttConsumerCallback(client, options, topic, qos));
            log.info("--添加回调处理类");
            log.debug("--添加回调处理类");
            client.connect(options);
        } catch (Exception e) {
            log.info("装载实例或订阅主题异常:" + e);
@@ -121,7 +126,7 @@
     */
    public void subscribe(String topic, int qos) {
        try {
            log.info("topic:" + topic);
            log.debug("topic:" + topic);
            client.subscribe(topic, qos);
        } catch (MqttException e) {
            e.printStackTrace();
@@ -130,8 +135,8 @@
    /**
     * 发布,非持久化
     *
     *  qos根据文档设置为1
     * <p>
     * qos根据文档设置为1
     *
     * @param topic
     * @param msg
@@ -144,30 +149,32 @@
     * 发布
     */
    public static void publish(int qos, boolean retained, String topic, String pushMessage) {
        log.info("【主题】:" + topic + "【qos】:" + qos + "【pushMessage】:" + pushMessage);
        MqttMessage message = new MqttMessage();
        message.setQos(qos);
        message.setRetained(retained);
        try {
            message.setPayload(pushMessage.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            log.error("mqtt编码异常:" + e.getMessage());
        }
        MqttTopic mTopic = client.getTopic(topic);
        if (null == mTopic) {
            log.error("topic:" + topic + " 不存在");
        }
        MqttDeliveryToken token;
        try {
            token = mTopic.publish(message);
            token.waitForCompletion();
            if (token.isComplete()) {
                log.info("消息发送成功");
        if (client != null) {
            log.debug("【主题】:" + topic + "【qos】:" + qos + "【pushMessage】:" + pushMessage);
            MqttMessage message = new MqttMessage();
            message.setQos(qos);
            message.setRetained(retained);
            try {
                message.setPayload(pushMessage.getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                log.error("mqtt编码异常:" + e.getMessage());
            }
        } catch (MqttPersistenceException e) {
            log.error("mqtt持久异常:" + e.getMessage());
        } catch (MqttException e) {
            log.error("mqtt异常:" + e.getMessage());
            MqttTopic mTopic = client.getTopic(topic);
            if (null == mTopic) {
                log.error("topic:" + topic + " 不存在");
            }
            MqttDeliveryToken token;
            try {
                token = mTopic.publish(message);
                token.waitForCompletion();
                if (token.isComplete()) {
                    log.debug("消息发送成功");
                }
            } catch (MqttPersistenceException e) {
                log.error("mqtt持久异常:" + e.getMessage());
            } catch (MqttException e) {
                log.error("mqtt异常:" + e.getMessage());
            }
        }
    }
}