【MQTT】使用MQTT在Spring Boot项目中实现异步消息通信
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.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
public class MqttPublisher {
private MqttClient mqttClient;
private final String brokerUrl = "tcp://localhost:1883";
private final String clientId = "JavaClient";
private final MemoryPersistence memoryPersistence = new MemoryPersistence();
public void connect() throws MqttException {
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);
mqttClient = new MqttClient(brokerUrl, clientId, memoryPersistence);
mqttClient.connect(connOpts);
}
public void publish(String topic, String payload) throws MqttException {
MqttMessage message = new MqttMessage(payload.getBytes());
mqttClient.publish(topic, message);
}
public void disconnect() throws MqttException {
if (mqttClient.isConnected()) {
mqttClient.disconnect();
}
}
public static void main(String[] args) {
MqttPublisher publisher = new MqttPublisher();
try {
publisher.connect();
publisher.publish("mqtt/example", "Hello MQTT");
publisher.disconnect();
} catch (MqttException e) {
e.printStackTrace();
}
}
}
这段代码展示了如何在Java中使用Eclipse Paho客户端库连接到MQTT代理,发布消息到特定的主题,并在完成消息发送后断开连接。这是一个简化的例子,用于演示如何在Spring Boot项目中实现MQTT消息的发送。
评论已关闭