EMQX安装和Java订阅、发布mqtt消息
EMQX是一个开源的MQTT消息代理,可以用于物联网设备、移动应用等,它支持MQTT、MQTT over WebSocket、TLS/SSL等协议。
EMQX的安装:
在Linux上安装EMQX,可以通过Docker或者下载二进制包进行安装。
使用Docker安装:
docker run -d --name emqx -p 1883:1883 -p 8083:8083 -p 8084:8084 -p 18083:18083 emqx/emqx
下载二进制包安装:
wget https://www.emqx.io/downloads/stable/4.3.14/emqx-4.3.14-otp24.2.1-1-ubuntu20.04-amd64.zip unzip emqx-4.3.14-otp24.2.1-1-ubuntu20.04-amd64.zip cd emqx ./bin/emqx start
Java使用Paho客户端进行MQTT订阅和发布:
首先,添加Paho客户端依赖到你的项目中。如果你使用Maven,可以添加以下依赖:
<dependency> <groupId>org.eclipse.paho</groupId> <artifactId>org.eclipse.paho.client.mqttv3</artifactId> <version>1.2.5</version> </dependency>
以下是Java代码示例,实现了MQTT消息的订阅和发布:
import org.eclipse.paho.client.mqttv3.*; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; public class MqttPubSub { public static void main(String[] args) { String broker = "tcp://localhost:1883"; String topic = "test/topic"; String content = "Hello, MQTT!"; String clientId = "JavaClient"; try { MqttClient sampleClient = new MqttClient(broker, clientId, new MemoryPersistence()); MqttConnectOptions connOpts = new MqttConnectOptions(); connOpts.setCleanSession(true); System.out.println("Connecting to broker: " + broker); sampleClient.connect(connOpts); System.out.println("Connected"); // 订阅消息 sampleClient.subscribe(topic); System.out.println("Subscribed to topic: " + topic); // 发布消息 MqttMessage message = new MqttMessage(content.getBytes()); message.setQos(2); sampleClient.publish(topic, message); System.out.println("Message published"); // 注册回调函数处理接收到的消息 sampleClient.setCallback(new MqttCallback() { public void messageArrived(String
评论已关闭