本篇记录一下MQTT服务器,客户端,JAVA客户端的选择开发与测试

MQTT服务端选择与安装过程;
MQTT客户端测试工具安装与测试;
MQTT JAVA客户端的选择与开发,测试


MQTT服务器选择与安装

目前主流的开源MQTT服务器主要是以下3个:
1) EMQX:github 4882 stars
2) Mosquitto:github 1645 stars
3) Apollo:ActiveMQ的升级版,github 109 stars

我们选择EMQX作为本次MQTT的服务器,首先去EMQ官网去下载EMQX安装版,截止目前最新版本已到V4.0.4

安装步骤请参考官网给出的帮助文档

按照官网操作无法启动服务,卡在emqx start看过来
  这步很坑的,一定要需要系统先安装好ERLANG开发环境,ERLANG跳转地址,可能是因为EMQX是用ERLANG来解释或开发的

安装启动完成后,如果是安装在本机,可以在浏览器中打开http://127.0.0.1:18083,输入默认用户名“admin”和默认密码“public”,能顺利进入管理控制台说明EMQX服务器安装完成。
微信截图_20200316231950.png

MQTT客户端安装与测试

客户端测试工具建议使用MQTTBox

MQTTBox有两种使用的方式:一种为Chrome插件;另外一种为Windows程序安装。

1) Chrome插件直接去Chrome插件市场搜索mqttbox即可(需要翻墙)
2) Windows安装包位置:点击下载

连接MQTT服务器:

参考下图设置连接服务器,协议选择mqtt/tcp ; Host端口为1883;
其它参数暂不影响测试,有兴趣自行研究。

微信截图_20200316232820.png

成功连接服务器,Connected图标会显示为绿色
微信截图_20200316233123.png

增加一个订阅者

订单topic为 "hello";Qos 为默认0

微信截图_20200316233356.png

增加一个发布者

发布一个topic为"hello" 的一段消息{"hello":"world"},Qos默认为0

消息发布后,订阅者窗口马上会收到这段消息。至此,客户端测试就完成。
微信截图_20200316233529.png

MQTT JAVA客户端开发与测试

JAVA客户端选择
EMQX SDK_TOOLS上罗列的几乎所有开发语言下的开源客户端工具。JAVA下的SDK目前主要有Eclipse Paho,Xenqtt,MeQanTT,mqtt-client。

因为Spring 的 Integration Endpoints去连接官方支持DEMO里面用的就是Eclipse Paho,所以本次JAVA客户端我们选择的也是Eclipse Paho .

POM引入

  <dependency>
            <groupId>org.eclipse.paho</groupId>
            <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
            <version>1.2.0</version>
        </dependency>

发布端开发示例

 1 import org.eclipse.paho.client.mqttv3.MqttClient;
 2 import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
 3 import org.eclipse.paho.client.mqttv3.MqttException;
 4 import org.eclipse.paho.client.mqttv3.MqttMessage;
 5 import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
 6 
 7 /**
 8  * 发布端未例
 9  */
10 public class PublishSample {
11     public static void main(String[] args) {
12 
13         String topic = "mqtt/okok";
14         String content = "hello 哈哈1";
15         int qos = 1;
16         String broker = "tcp://127.0.0.1:1883";
17         String userName = "test";
18         String password = "test";
19         String clientId = "pubClient1";
20         // 内存存储
21         MemoryPersistence persistence = new MemoryPersistence();
22 
23         try {
24             // 创建客户端
25             MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
26             // 创建链接参数
27             MqttConnectOptions connOpts = new MqttConnectOptions();
28             // 在重新启动和重新连接时记住状态
29             connOpts.setCleanSession(false);
30             // 设置连接的用户名
31             connOpts.setUserName(userName);
32             connOpts.setPassword(password.toCharArray());
33             // 建立连接
34             sampleClient.connect(connOpts);
35             // 创建消息
36             MqttMessage message = new MqttMessage(content.getBytes());
37             // 设置消息的服务质量
38             message.setQos(qos);
39             // 发布消息
40             sampleClient.publish(topic, message);
41             // 断开连接
42             sampleClient.disconnect();
43             // 关闭客户端
44             sampleClient.close();
45         } catch (MqttException me) {
46             System.out.println("reason " + me.getReasonCode());
47             System.out.println("msg " + me.getMessage());
48             System.out.println("loc " + me.getLocalizedMessage());
49             System.out.println("cause " + me.getCause());
50             System.out.println("excep " + me);
51             me.printStackTrace();
52         }
53     }
54 }

订阅端发布实例

 1 import org.eclipse.paho.client.mqttv3.*;
 2 import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
 3 
 4 /**
 5  * 订阅端
 6  */
 7 public class SubscribeSample {
 8     public static void main(String[] args) throws MqttException {
 9         String HOST = "tcp://127.0.0.1:1883";
10         String TOPIC = "mqtt/okok";
11         int qos = 1;
12         String clientid = "subClient1";
13         String userName = "test";
14         String passWord = "test";
15         try {
16             // host为主机名,test为clientid即连接MQTT的客户端ID,一般以客户端唯一标识符表示,MemoryPersistence设置clientid的保存形式,默认为以内存保存
17             MqttClient client = new MqttClient(HOST, clientid, new MemoryPersistence());
18             // MQTT的连接设置
19             MqttConnectOptions options = new MqttConnectOptions();
20             // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录,这里设置为true表示每次连接到服务器都以新的身份连接
21             options.setCleanSession(true);
22             // 设置连接的用户名
23             options.setUserName(userName);
24             // 设置连接的密码
25             options.setPassword(passWord.toCharArray());
26             // 设置超时时间 单位为秒
27             options.setConnectionTimeout(10);
28             // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线,但这个方法并没有重连的机制
29             options.setKeepAliveInterval(20);
30             // 设置回调函数
31             client.setCallback(new MqttCallback() {
32 
33                 @Override
34                 public void connectionLost(Throwable cause) {
35                     System.out.println("connectionLost");
36                 }
37 
38                 @Override
39                 public void messageArrived(String topic, MqttMessage message) throws Exception {
40                     System.out.println("topic:"+topic);
41                     System.out.println("Qos:"+message.getQos());
42                     System.out.println("message content:"+new String(message.getPayload()));
43 
44                 }
45 
46                 @Override
47                 public void deliveryComplete(IMqttDeliveryToken token) {
48                     System.out.println("deliveryComplete---------"+ token.isComplete());
49                 }
50 
51             });
52             client.connect(options);
53             //订阅消息
54             client.subscribe(TOPIC, qos);
55         } catch (Exception e) {
56             e.printStackTrace();
57         }
58     }
59 }

下一篇:MQTT整合进Spring Mvc

更多参考网站:

1.EMQX帮助中心 https://docs.emqx.io/broker/latest/cn/
2.Spring MQTT Support https://docs.spring.io/spring-integration/docs/5.0.8.RELEASE/reference/html/mqtt.html