Newer
Older
newfiber-termite / newfiber-termites / newfiber-termites-dataup / src / main / java / com / newfiber / termite / config / MqttConfig.java
@xiongkai xiongkai on 2 Jul 2 KB 集成mq
package com.newfiber.termite.config;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;

@Slf4j
//@Configuration
public class MqttConfig {
    /**
     * MQTT服务端地址
     */
    @Value("${spring.mqtt.url}")
    private String serverURI;

    /**
     * 发布客户端id(不能重复)
     */
    @Value("${spring.mqtt.clientIdPub}")
    private String clientIdPub;

    /**
     * 用户名
     */
    @Value("${spring.mqtt.username}")
    private String username;

    /**
     * 密码
     */
    @Value("${spring.mqtt.password}")
    private String password;

    /**
     * mqtt发送消息客户端
     */
    private static MqttClient sendMqttClient;

    public static MqttClient getSendClient() {
        return sendMqttClient;
    }


    static MqttConnectOptions opts;

    @Bean
    MqttConnectOptions mqttConnectOptions() {
        try {
            opts = new MqttConnectOptions();
            opts.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
            opts.setMaxReconnectDelay(5 * 1000);
            opts.setConnectionTimeout(2 * 1000);
            opts.setHttpsHostnameVerificationEnabled(false);
            opts.setCleanSession(false);
            opts.setKeepAliveInterval(5);
            opts.setAutomaticReconnect(true);
            opts.setUserName(username);
            opts.setPassword(password.toCharArray());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return opts;
    }

    @Bean
    MqttClient sendMqttClient() {
        MqttClient sendClient = null;
        try {

            MemoryPersistence persistence = new MemoryPersistence();
            sendClient = new MqttClient(serverURI, clientIdPub + "send", persistence);
            IMqttToken token = sendClient.connectWithResult(opts);
            token.waitForCompletion();
            sendMqttClient = sendClient;
        } catch (MqttException e) {
            log.error(e.getMessage());
        }
        return sendMqttClient;
    }

}