【EMQX实践】SpringBoot集成EMQX客户端组件
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
public class EMQXClientExample {
public static void main(String[] args) {
String broker = "tcp://your-emqx-host:1883";
String clientId = "JavaClient";
MemoryPersistence persistence = new MemoryPersistence();
try {
MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);
System.out.println("Connecting to broker: " + broker);
sampleClient.connect(connOpts);
System.out.println("Connected");
String topic = "emqx/test";
String content = "message from Java client";
MqttMessage message = new MqttMessage(content.getBytes());
message.setQos(2);
sampleClient.publish(topic, message);
System.out.println("Message is published");
sampleClient.disconnect();
System.out.println("Disconnected");
System.exit(0);
} catch (MqttException me) {
System.out.println("reason " + me.getReasonCode());
System.out.println("msg " + me.getMessage());
System.out.println("loc " + me.getLocalizedMessage());
System.out.println("cause " + me.getCause());
System.out.println("exiting with code " + 1);
}
}
}
这段代码演示了如何在Java中使用Eclipse Paho客户端库连接到EMQX,发布一条消息到特定主题,然后断开连接。需要替换your-emqx-host
为EMQX服务器的实际IP或主机名,并确保EMQX服务器正在运行,并且网络之间的端口1883(或其他配置的端口)是开放的。
评论已关闭