|
|
@@ -898,47 +898,22 @@ public class IotDataTransferService {
|
|
|
*/
|
|
|
private void createMqttConnection(String username, String password) {
|
|
|
try {
|
|
|
- // 创建MqttBaseConfig实例并设置参数
|
|
|
- MqttBaseConfig mqttBaseConfig = new MqttBaseConfig();
|
|
|
- // 手动设置所有MQTT配置参数
|
|
|
- mqttBaseConfig.setUsername(username);
|
|
|
- mqttBaseConfig.setPassword(password);
|
|
|
- mqttBaseConfig.setHostUrl(MQTT_URL);
|
|
|
- mqttBaseConfig.setMsgTopic(MQTT_TOPIC);
|
|
|
- mqttBaseConfig.setKeepAliveInterval(KEEP_ALIVE_INTERVAL);
|
|
|
- mqttBaseConfig.setCompletionTimeout(COMPLETION_TIMEOUT);
|
|
|
-
|
|
|
- // 创建MqttOutConfig实例
|
|
|
- MqttOutConfig mqttOutConfig = new MqttOutConfig();
|
|
|
- mqttOutConfig.mqttBaseConfig = mqttBaseConfig;
|
|
|
-
|
|
|
- // 使用Spring的ApplicationContext手动创建Bean
|
|
|
- ApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
|
|
|
- if (context == null) {
|
|
|
- throw new IllegalStateException("ApplicationContext未找到,无法创建MQTT相关Bean");
|
|
|
- }
|
|
|
-
|
|
|
- // 注册MqttBaseConfig为Bean
|
|
|
- ConfigurableListableBeanFactory beanFactory = ((ConfigurableApplicationContext) context).getBeanFactory();
|
|
|
- beanFactory.registerSingleton("mqttBaseConfig", mqttBaseConfig);
|
|
|
-
|
|
|
- // 创建并注册mqttClientFactory
|
|
|
+ // 直接创建和配置MQTT客户端,不依赖Spring自动配置
|
|
|
+ // 1. 创建MqttConnectOptions
|
|
|
MqttConnectOptions options = new MqttConnectOptions();
|
|
|
- options.setServerURIs(new String[]{mqttBaseConfig.getHostUrl()});
|
|
|
- options.setUserName(mqttBaseConfig.getUsername());
|
|
|
- options.setPassword(mqttBaseConfig.getPassword().toCharArray());
|
|
|
- options.setKeepAliveInterval(mqttBaseConfig.getKeepAliveInterval());
|
|
|
+ options.setServerURIs(new String[]{MQTT_URL});
|
|
|
+ options.setUserName(username);
|
|
|
+ options.setPassword(password.toCharArray());
|
|
|
+ options.setKeepAliveInterval(KEEP_ALIVE_INTERVAL);
|
|
|
|
|
|
+ // 2. 创建DefaultMqttPahoClientFactory
|
|
|
DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
|
|
|
factory.setConnectionOptions(options);
|
|
|
- beanFactory.registerSingleton("mqttClientFactory", factory);
|
|
|
-
|
|
|
- // 注册MqttOutConfig为Bean
|
|
|
- beanFactory.registerSingleton("mqttOutConfig", mqttOutConfig);
|
|
|
|
|
|
- // 获取mqttGateway
|
|
|
- this.mqttGateway = context.getBean(MqttOutConfig.MqttGateway.class);
|
|
|
- log.info("MQTT连接创建成功");
|
|
|
+ // 3. 由于@MessagingGateway需要Spring容器管理,我们需要确保Spring已经正确初始化了网关
|
|
|
+ // 这里我们不手动创建网关,而是依赖Spring自动创建,但是需要确保MqttOutConfig类不再被Spring自动配置
|
|
|
+ // 所以我们已经移除了MqttOutConfig和MqttInConfig类上的@Configuration注解和@Bean注解
|
|
|
+ log.info("MQTT连接参数配置完成,用户名:{}", username);
|
|
|
} catch (Exception e) {
|
|
|
log.error("创建MQTT连接失败: {}", e.getMessage(), e);
|
|
|
throw new RuntimeException("创建MQTT连接失败", e);
|