==pom依赖==
<dependency> <groupId>org.eclipse.paho</groupId> <artifactId>org.eclipse.paho.client.mqttv3</artifactId> <version>1.2.1</version> </dependency>
==Java样例代码==
【工具类】
package examples; import org.eclipse.paho.client.mqttv3.*; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; import java.util.HashMap; import java.util.Map; /** * MQTT Client * * @author chunui.qu */ public class MqttUtils { private final Map<String, MqttClient> clientMap = new HashMap<>(); /** * 构造函数 */ private MqttUtils() { } /** * 单例模式 */ private static class SingletonInstance { private static final MqttUtils INSTANCE = new MqttUtils(); } /** * 获取对象句柄 */ public static MqttUtils getInstance() { return SingletonInstance.INSTANCE; } /** * 创建客户端连接 * * @param clientId clientId * @return 结果 */ public MqttClient getMqttClient(String clientId) { if (clientMap.containsKey(clientId)) { return clientMap.get(clientId); } String serverUrl = "tcp://36.137.154.92:1883"; String username = "root"; String password = "test123"; try { MqttConnectOptions options = new MqttConnectOptions(); // 设置连接的用户名 options.setUserName(username); // 设置连接的密码 options.setPassword(password.toCharArray()); // 设置是否清空session // 设置为false表示服务器会保留客户端的连接记录 // 设置为true表示每次连接到服务器都以新的身份连接 options.setCleanSession(false); // 设置会话心跳时间 options.setAutomaticReconnect(true); // 设置超时时间,单位为秒 options.setConnectionTimeout(10); // 设置会话心跳时间,单位为秒 // 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线,但这个方法并没有重连的机制 options.setKeepAliveInterval(20); // host:服务连接地址 // clientIId:连接MQTT的客户端ID,一般以唯一标识符表示 // MemoryPersistence:clientId的保存形式,默认为以内存保存 MqttClient client = new MqttClient(serverUrl, clientId, new MemoryPersistence()); // 设置回调 MyMqttCallback callback = new MyMqttCallback(); client.setCallback(callback); // 建立连接 client.connect(options); // 按clientId保存 clientMap.put(clientId, client); return client; } catch (MqttException e) { e.printStackTrace(); return null; } } static class MyMqttCallback implements MqttCallbackExtended { @Override public void connectComplete(boolean b, String s) { System.out.println("连接成功"); } @Override public void connectionLost(Throwable throwable) { System.out.println("连接断开:" + throwable.getMessage()); } @Override public void messageArrived(String topic, MqttMessage message) { System.out.println("接收消息主题:" + topic); System.out.println("接收消息Qos:" + message.getQos()); System.out.println("接收消息内容:" + new String(message.getPayload())); } @Override public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) { System.out.println("发送成功:" + iMqttDeliveryToken.isComplete()); } } }
【生产者】
package examples; import org.eclipse.paho.client.mqttv3.MqttClient; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.eclipse.paho.client.mqttv3.MqttTopic; /** * PublishDemo * * @author Chunhui.Qu */ public class PublishDemo { public static void main(String[] args) { MqttUtils mqttUtils = MqttUtils.getInstance(); MqttClient mqttClient = mqttUtils.getMqttClient("publish_client"); MqttTopic topic1 = mqttClient.getTopic("qch_test1"); MqttMessage msg1 = new MqttMessage(); msg1.setPayload("第1个消息".getBytes()); msg1.setQos(2); msg1.setRetained(true); try { topic1.publish(msg1); } catch (MqttException e) { e.printStackTrace(); } MqttTopic topic2 = mqttClient.getTopic("qch_test2"); MqttMessage msg2 = new MqttMessage(); msg2.setPayload("第2个消息".getBytes()); msg2.setQos(2); msg2.setRetained(true); try { topic2.publish(msg2); } catch (MqttException e) { e.printStackTrace(); } } }
【消费者】
package examples; import org.eclipse.paho.client.mqttv3.MqttClient; import org.eclipse.paho.client.mqttv3.MqttException; /** * SubscribeDemo * * @author Chunhui.Qu */ public class SubscribeDemo { public static void main(String[] args) { MqttUtils mqttUtils = MqttUtils.getInstance(); MqttClient mqttClient = mqttUtils.getMqttClient("subscribe_client"); int[] qos = {2, 2}; String[] topics = {"qch_test1", "qch_test2"}; try { mqttClient.subscribe(topics, qos); } catch (MqttException e) { e.printStackTrace(); } } }
==执行结果==
连接成功 接收消息主题:qch_test1 接收消息Qos:2 接收消息内容:第1个消息 接收消息主题:qch_test2 接收消息Qos:2 接收消息内容:第2个消息