1. 添加依赖
在pom.xml
中添加Eclipse Paho MQTT库的依赖项:
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.5</version>
</dependency>
2. 创建MQTT客户端类
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
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 MqttExample {
private static final String BROKER_URL = "tcp://broker.hivemq.com:1883"; // 公共MQTT Broker
private static final String CLIENT_ID = "JavaClient";
private static final String TOPIC = "test/topic";
private MqttClient client;
private MqttConnectOptions connOpts;
public MqttExample() {
try {
// 创建MqttClient实例
client = new MqttClient(BROKER_URL, CLIENT_ID, new MemoryPersistence());
// 设置连接选项
connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true); // 是否清除会话
connOpts.setAutomaticReconnect(true); // 自动重连
connOpts.setConnectionTimeout(10); // 连接超时时间
connOpts.setKeepAliveInterval(20); // 心跳间隔时间
// 设置回调函数
client.setCallback(new MqttCallback() {
@Override
public void connectionLost(Throwable cause) {
System.out.println("Connection lost: " + cause.getMessage());
// 当连接丢失时触发
}
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
System.out.println("Message received on topic " + topic + ":\n\t" + new String(message.getPayload()));
// 当消息到达时触发
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
System.out.println("Delivery complete: " + token.isComplete());
// 当消息传递完成时触发
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}
public void connect() {
try {
// 连接到MQTT Broker
client.connect(connOpts);
System.out.println("Connected to broker: " + BROKER_URL);
} catch (MqttException e) {
e.printStackTrace();
}
}
public void subscribe(String topic) {
try {
client.subscribe(topic);
System.out.println("Subscribed to topic: " + topic);
} catch (MqttException e) {
e.printStackTrace();
}
}
public void publish(String topic, String content, int qos) {
try {
MqttMessage message = new MqttMessage(content.getBytes());
message.setQos(qos); // 设置QoS级别
client.publish(topic, message);
System.out.println("Message published on topic " + topic + ": " + content);
} catch (MqttException e) {
e.printStackTrace();
}
}
public void disconnect() {
try {
client.disconnect();
System.out.println("Disconnected from broker");
} catch (MqttException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
MqttExample example = new MqttExample();
// 连接到Broker
example.connect();
// 订阅主题
example.subscribe(TOPIC);
// 发布消息
example.publish(TOPIC, "Hello MQTT!", 1);
// 模拟长时间运行,等待消息到来
try {
Thread.sleep(30000); // 保持连接30秒
} catch (InterruptedException e) {
e.printStackTrace();
}
// 断开连接
example.disconnect();
}
}