在Spring Boot项目中集成和使用MQTT
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.springframework.stereotype.Service;
@Service
public class MqttService {
private MqttClient client;
private String broker = "tcp://iot.eclipse.org:1883";
private String clientId = "JavaClient";
private MqttConnectOptions connOpts;
public MqttService() throws Exception {
client = new MqttClient(this.broker, this.clientId);
connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);
System.out.println("Connecting to broker: " + broker);
client.connect(connOpts);
client.setCallback(new MqttCallback() {
public void messageArrived(String topic, MqttMessage message) throws Exception {
System.out.println("Message arrived: " + new String(message.getPayload()));
}
public void connectionLost(Throwable cause) {
System.out.println("Connection lost");
}
public void deliveryComplete(IMqttDeliveryToken token) {
System.out.println("Delivery complete");
}
});
client.subscribe("java/temperature");
System.out.println("Subscribed to topic: java/temperature");
}
public void publish(String topic, String message) throws Exception {
MqttMessage mqttMessage = new MqttMessage(message.getBytes());
MqttDeliveryToken token = client.publish(topic, mqttMessage);
token.waitForCompletion();
System.out.println("Message published");
}
}
这段代码展示了如何在Spring Boot项目中初始化和使用MQTT客户端。它首先创建了一个MqttClient
实例,并设置了连接选项。然后,它连接到MQTT代理,设置了一个回调函数来处理到达的消息,订阅了一个主题,并提供了一个发布消息的方法。这个例子简洁明了,并且包含了在实际应用中可能需要的基本组件。
评论已关闭