实现ApplicationRunner接口run 方法
@Slf4j
@Component
@Order(value = 2) //指定执行顺序
@EnableAsync //异步执行
public class MilitaryMqttApplication implements ApplicationRunner {
@Resource
private MqttService mqttService;
@Resource
private MQTTProps mqttProps;
public MilitaryMqttApplication(MqttService mqttService, MQTTProps mqttProps) {
this.mqttService = mqttService;
this.mqttProps = mqttProps;
}
@Override
@Async
public void run(ApplicationArguments args) throws Exception {
try {
mqttService.connect();
mqttService.subscribe(mqttProps.getClient().getTopics());
} catch (MqttException e) {
// 尝试重新连接
mqttService.reconnect();
mqttService.subscribe(mqttService.getSubscribed());
}
}
}