package com.fuyuanshen.global.mqtt.config;

import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;


@Configuration
public class MqttConfiguration {
    @Autowired
    private MqttPropertiesConfig mqttPropertiesConfig;
    /**  创建连接工厂 **/
    @Bean
    public MqttPahoClientFactory mqttPahoClientFactory(){
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(true); //设置新会话
        options.setUserName(mqttPropertiesConfig.getUsername());
        options.setPassword(mqttPropertiesConfig.getPassword().toCharArray());
        options.setServerURIs(new String[]{mqttPropertiesConfig.getUrl()});
        options.setAutomaticReconnect(true); // 启用自动重连
        options.setConnectionTimeout(10); // 设置连接超时时间
        options.setKeepAliveInterval(60); // 设置心跳间隔
        factory.setConnectionOptions(options);
        return factory;
    }
 
}