44 lines
1.5 KiB
Java
44 lines
1.5 KiB
Java
package com.muyu.mqtt.config;
|
||
|
||
import com.muyu.mqtt.service.MqttService;
|
||
import lombok.extern.log4j.Log4j2;
|
||
import org.eclipse.paho.client.mqttv3.MqttClient;
|
||
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
|
||
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
|
||
import org.springframework.context.annotation.Bean;
|
||
import org.springframework.context.annotation.Configuration;
|
||
|
||
import java.util.UUID;
|
||
|
||
/**
|
||
* @author DongZl
|
||
* @description: Mqtt配置
|
||
* @Date 2023-11-24 下午 02:06
|
||
*/
|
||
@Log4j2
|
||
//@Configuration
|
||
public class MqttConfig {
|
||
|
||
@Bean
|
||
public MqttClient initClient(MqttProper mqttProper, MqttService mqttService){
|
||
try {
|
||
log.info("mqtt服务器初始化开始");
|
||
long startTime = System.currentTimeMillis();
|
||
MqttClient client = new MqttClient(mqttProper.getBroker(),
|
||
UUID.randomUUID().toString(),
|
||
new MemoryPersistence());
|
||
// 连接参数
|
||
MqttConnectOptions options = new MqttConnectOptions();
|
||
options.setConnectionTimeout(60);
|
||
options.setKeepAliveInterval(60);
|
||
log.info("mqtt服务器初始化结束, 耗时:[{}MS]", System.currentTimeMillis() - startTime);
|
||
client.connect(options);
|
||
client.setCallback(mqttService);
|
||
client.subscribe(mqttProper.getTopic(), 0);
|
||
return client;
|
||
}catch (Exception e) {
|
||
throw new RuntimeException(e);
|
||
}
|
||
}
|
||
}
|