Java中使用MQTT协议
2021-04-11 19:33:11
## SpringBoot中的用法
### 首先,在pom文件中添加相关依赖
```java
<dependency>
<groupId>org.fusesource.mqtt-client</groupId>
<artifactId>mqtt-client</artifactId>
<version>1.12</version>
</dependency>
```
然后便可以使用mqtt对象。配置好相关参数
```java
MQTT mqtt = new MQTT();
mqtt.setHost("localhost", 1883);
// or
mqtt.setHost("tcp://localhost:1883");
mqtt.setUserName(username);
mqtt.setPassword(password);
```
建立连接
```java
BlockingConnection connection = mqtt.blockingConnection();
connection.connect();
```
可以使用publish方法将消息发布到主题
```java
connection.publish("foo", "Hello".getBytes(), QoS.AT_LEAST_ONCE, false);
```
可以使用subscribe方法来订阅多个主题
```java
Topic[] topics = {new Topic("foo", QoS.AT_LEAST_ONCE)};
byte[] qoses = connection.subscribe(topics);
```
使用receive和ack方法接收并确认消息
```java
Message message = connection.receive(); //若未收到message将不会进入下一步
System.out.println(message.getTopic());
byte[] payload = message.getPayload();
// process the message then:
message.ack();
```
断开连接
```java
connection.disconnect();
```