项目已发布到github https://github.com/gaoyf95/springboot-mqtt
结构
Server side 构成
- broker (mqtt核心:用于消息的发送管理)
- Application Server用于处理RestFul的请求,转发为Mqtt消息
- Publisher 本质是Mqtt client用于发布server端消息
- Subscriber 本质是Mqtt client用于订阅client端消息,并显示
- Client side
- Publisher用于发布client端消息
- Subscriber用于订阅server端的消息
- Client 用于发送RestFul 请求给Application Server触发消息pub/sub
总结:从结构上Broker算是Mqtt的本质上的Server端,从业务上讲封装了Mqtt Client pub/sub的Application server和Broker共同构成了业务上的Server端
构建springboot项目
1. 使用idea springboot initializer 初始化springboot工程
使用springboot版本2.1.5.RELEASE
2. pom中添加
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-stream</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-mqtt</artifactId>
</dependency>
3. MQTT Configuration
- 配置broker地址,
- 端口号,
- 是否使用ssl,
- 用户名
- 密码
public abstract class MQTTConfig {
protected String ip = "127.0.0.1";
/**
* qos0 对于client而言,有且仅发一次publish包,对于broker而言,有且仅发一次publish,简而言之,就是仅发一次包,是否收到完全不管,适合那些不是很重要的数据。
* qos1 这个交互就是多了一次ack的作用,但是会有个问题,尽管我们可以通过确认来保证一定收到客户端或服务器的message,但是我们却不能保证message仅有一次,
* 也就是当client没收到service的puback或者service没有收到client的puback,那么就会一直发送publisher
* qos2可以实现仅仅接受一次message,其主要原理(对于publisher而言),
* publisher和broker进行了缓存,其中publisher缓存了message和msgID,而broker缓存了msgID,两方都做记录所以可以保证消息不重复,
* 但是由于记录是需要删除的,这个删除流程同样多了一倍
*/
protected int qos = 2;
protected Boolean hasSSL = false; //默认SSL关闭
protected Integer port = 1883; //默认端口
protected String username = "账号";
protected String password = "密码";
protected String TCP = "tcp://";
protected String SSL = "ssl://";
/**
* Custom Configuration
*/
protected abstract void config(String ip, Integer port, Boolean ssl, Boolean withUserNamePass);
/**
* Default Configuration
*/
protected abstract void config();
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public int getQos() {
return qos;
}
public void setQos(int qos) {
this.qos = qos;
}
public Boolean ge