From 342284d12ce3a0f60dbc3584cff385761412429f Mon Sep 17 00:00:00 2001 From: lingyunxsh Date: Tue, 13 May 2025 21:32:51 +0800 Subject: [PATCH] =?UTF-8?q?mqtt=E5=88=9D=E5=A7=8B=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/yupi/project/config/MqttConfig.java | 33 +++++++++---------- 1 file changed, 16 insertions(+), 17 deletions(-) diff --git a/springboot-init-main/src/main/java/com/yupi/project/config/MqttConfig.java b/springboot-init-main/src/main/java/com/yupi/project/config/MqttConfig.java index 7e6d07b..6b1358b 100644 --- a/springboot-init-main/src/main/java/com/yupi/project/config/MqttConfig.java +++ b/springboot-init-main/src/main/java/com/yupi/project/config/MqttConfig.java @@ -8,7 +8,6 @@ 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.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.util.StringUtils; @@ -25,7 +24,7 @@ public class MqttConfig { private final MqttProperties mqttProperties; private final MqttCallbackHandler mqttCallbackHandler; - @Autowired // Autowire the MqttClient bean defined below + // No @Autowired here. This field will be set by the mqttClientBean() method. private MqttClient mqttClient; @Bean @@ -37,55 +36,55 @@ public class MqttConfig { if (StringUtils.hasText(mqttProperties.getPassword())) { options.setPassword(mqttProperties.getPassword().toCharArray()); } - options.setAutomaticReconnect(true); // Enable automatic reconnect - options.setCleanSession(true); // Start with a clean session + options.setAutomaticReconnect(true); + options.setCleanSession(true); options.setConnectionTimeout(mqttProperties.getConnectionTimeout()); options.setKeepAliveInterval(mqttProperties.getKeepAliveInterval()); - // options.setWill(...) // Configure Last Will and Testament if needed return options; } - @Bean // Bean method name will be the bean name by default: "mqttClientBean" + @Bean public MqttClient mqttClientBean(MqttConnectOptions mqttConnectOptions) throws MqttException { String clientId = mqttProperties.getClientIdPrefix() + UUID.randomUUID().toString().replace("-", ""); + // Create the client instance MqttClient client = new MqttClient(mqttProperties.getBrokerUrl(), clientId, new MemoryPersistence()); client.setCallback(mqttCallbackHandler); - // Pass the client instance to the handler so it can subscribe on connectComplete - mqttCallbackHandler.setMqttClient(client); - return client; + mqttCallbackHandler.setMqttClient(client); + + // Assign the created client to the instance field for @PostConstruct/@PreDestroy usage + this.mqttClient = client; + return client; // Return it to be managed by Spring as a bean } @PostConstruct public void connect() { try { - // Use the autowired mqttClient field if (this.mqttClient != null && !this.mqttClient.isConnected()) { log.info("Attempting to connect to MQTT broker: {} with client ID: {}", mqttProperties.getBrokerUrl(), this.mqttClient.getClientId()); - this.mqttClient.connect(mqttConnectOptions()); // mqttConnectOptions() provides the bean - // Subscription logic is now in MqttCallbackHandler.connectComplete + // Pass the MqttConnectOptions bean directly to the connect method + this.mqttClient.connect(mqttConnectOptions()); } else if (this.mqttClient == null) { - log.error("MqttClient (autowired) is null, cannot connect."); + log.error("MqttClient instance is null (was not set by mqttClientBean), cannot connect."); } } catch (MqttException e) { log.error("Error connecting to MQTT broker: ", e); - // Consider retry logic or application failure based on requirements } } @PreDestroy public void disconnect() { try { - // Use the autowired mqttClient field if (this.mqttClient != null && this.mqttClient.isConnected()) { log.info("Disconnecting from MQTT broker: {}", this.mqttClient.getServerURI()); this.mqttClient.disconnect(); log.info("Successfully disconnected from MQTT broker."); } if (this.mqttClient != null) { - this.mqttClient.close(); + // Ensure close is called even if disconnect fails or was not connected + this.mqttClient.close(); } } catch (MqttException e) { - log.error("Error disconnecting from MQTT broker: ", e); + log.error("Error disconnecting/closing MQTT client: ", e); } } } \ No newline at end of file