Springboot整合Mqtt:单例模式的Mqtt工具类

 

以下代码为单例模式,可支持的并发量受限,仅供mqtt测试,如需更高的并发量,参见其他博客,使用了多线程及多客户端进行并行发送。

package com.newlinker.mqtt_test.utils;

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;

import javax.annotation.PostConstruct;

import java.io.IOException;
import java.util.Objects;

import static com.sun.jmx.remote.internal.IIOPHelper.connect;

/**
 * @author cyl
 * @time 2023/4/24
 */
@Component
public class MqttClientUtil {
    @Value("${mqtt.username}")
    private String username;
    @Value("${mqtt.password}")
    private String password;
    @Value("${mqtt.url}")
    private String host;
    @Value("${mqtt.defaultTopic}")
    private String topic;
    @Value("${mqtt.clientId}")
    private String clientId;
    @Value("${mqtt.connectionTimeout}")
    private int timeout;
    @Value("${mqtt.keepAliveInterval}")
    private int interval;

    private MqttClient mqttClient;
    private MqttConnectOptions mqttConnectOptions;

    @PostConstruct
    private void init() throws IOException {
        connect(host,clientId);
    }

    /**
     * 连接mqtt
     * @param host
     * @param clientId
     */
    public void connect(String host,String clientId){
        try{
            mqttClient = new MqttClient(host,clientId,new MemoryPersistence());
            mqttConnectOptions = getMqttConnectOptions();
            mqttClient.connect(mqttConnectOptions);
        }catch (Exception e){
            System.out.println("mqtt服务连接异常!");
            e.printStackTrace();
        }
    }

   

    /**
     * 设置连接对象信息
     * setCleanSession  true 断开连接即清楚会话  false 保留连接信息 离线还会继续发消息
     * @return
     */
    private MqttConnectOptions getMqttConnectOptions(){
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setUserName(username);
        mqttConnectOptions.setPassword(password.toCharArray());
        mqttConnectOptions.setServerURIs(new String[]{host});
        mqttConnectOptions.setKeepAliveInterval(interval);
        mqttConnectOptions.setConnectionTimeout(timeout);
        mqttConnectOptions.setCleanSession(true);
        return mqttConnectOptions;
    }

    /**
     *mqtt连接状态
     * @return
     */
    private boolean isConnect(){
        if(Objects.isNull(this.mqttClient)){
            return false;
        }
        return mqttClient.isConnected();
    }

    /**
     * 设置重连
     * @throws Exception
     */
    private void reConnect() throws Exception{
        if(Objects.nonNull(this.mqttClient)){
            System.out.println("mqtt 服务已重新连接...");
            this.mqttClient.connect(this.mqttConnectOptions);
        }
    }

    /**
     * 断开连接
     * @throws Exception
     */
    public void closeConnect() throws Exception{
        if(Objects.nonNull(this.mqttClient)){
            System.out.println("mqtt 服务已断开连接...");
            this.mqttClient.disconnect();
        }
    }

    /**
     * 发布消息
     * @param topic
     * @param message
     * @param qos
     * @throws Exception
     */
    public void sendMessage(String topic,String message,int qos) throws Exception {
        if(Objects.nonNull(this.mqttClient) && this.mqttClient.isConnected()){
            MqttMessage mqttMessage = new MqttMessage();
            mqttMessage.setPayload(message.getBytes());
            mqttMessage.setQos(qos);

            MqttTopic mqttTopic = mqttClient.getTopic(topic);

            if(Objects.nonNull(mqttTopic)){
                try{
                    MqttDeliveryToken publish = mqttTopic.publish(mqttMessage);
                    if(publish.isComplete()){
                        //log.info("消息发送成功---->{}",message);
                    }
                }catch(Exception e){
                    System.out.println("消息发送异常!");
                    e.printStackTrace();
                }
            }
        }else{
            reConnect();
        }
    }
}

 

posted @ 2023-04-25 11:41  onecyl  阅读(285)  评论(0编辑  收藏  举报