1. Introduction
mica-mqtt based on t-io implement simple , low-latency , high-performance open source components of the Internet of Things. please refer to the mica-mqtt gitee source code mica-mqtt-example
module.
2. Function
- [x] Support MQTT v3.1, v3.1.1 and v5.0 protocols.
- [x] Support MQTT client client.
- [x] Support MQTT server server.
- [x] Support MQTT will message.
- [x] Support MQTT reserved messages.
- [x] Support custom message (mq) processing and forwarding to realize clustering.
- [x] MQTT client Alibaba Cloud mqtt connects to the demo.
- [x] Support GraalVM to compile native executable programs.
- [x] Support Spring boot project quick access (mica-mqtt-spring-boot-starter).
- [x] mica-mqtt-spring-boot-starter supports Prometheus + Grafana.
Three, to do
- [] Add websocket support (pre-researched successfully).
- [] Optimize the handling of mqtt session, and support v5.0
Four, update records
- 📝 The document adds instructions for cluster processing steps, adding will messages and usage scenarios for retained messages.
- ✨ Remove the qos2 parameter in the demonstration, and the performance loss is large to avoid misuse.
- ✨ Wills, retained messages, internal message forwarding abstraction.
- ✨ Add mica-mqtt-spring-boot-example. Thanks to wsq (@冷月宫主) pr.
- ✨ mica-mqtt-spring-boot-starter supports client access and server optimization. Thanks to wsq (@冷月宫主) pr.
- ✨ The mica-mqtt-spring-boot-starter server supports indicator collection. Can be connected to Prometheus + Grafana monitoring.
- ✨ When mqtt server accepts a connection, it first determines whether there are other connections for the clientId, and unbinds and closes other connections if there are.
- ⬆️ Upgrade mica-auto to 2.1.3. Fix ide multi-module incremental compilation problem.
Five, Spring boot quick access
5.1 Add dependency
<dependency>
<groupId>net.dreamlu</groupId>
<artifactId>mica-mqtt-spring-boot-starter</artifactId>
<version>1.0.2</version>
</dependency>
5.2 Server yml configuration
mqtt:
server:
enabled: true # 是否开启,默认:true
ip: 127.0.0.1 # 服务端 ip 默认:127.0.0.1
port: 5883 # 端口,默认:1883
name: Mica-Mqtt-Server # 名称,默认:Mica-Mqtt-Server
buffer-allocator: HEAP # 堆内存和堆外内存,默认:堆内存
heartbeat-timeout: 120000 # 心跳超时,单位毫秒,默认: 1000 * 120
read-buffer-size: 8092 # 接收数据的 buffer size,默认:8092
max-bytes-in-message: 8092 # 消息解析最大 bytes 长度,默认:8092
debug: true # 如果开启 prometheus 指标收集建议关闭
5.3 Server-side implementable interface (just register as Spring Bean)
interface | Do you have to | instruction |
---|---|---|
IMqttServerAuthHandler | Yes | For client authentication |
IMqttMessageListener | Yes | Message monitoring |
IMqttConnectStatusListener | Yes | Connection status monitoring |
IMqttSessionManager | no | session management |
IMqttMessageStore | Cluster yes, stand-alone no | Wills and retention message storage |
AbstractMqttMessageDispatcher | Cluster yes, stand-alone no | Message forwarding, (will, retained message forwarding) |
IpStatListener | no | t-io ip status monitoring |
5.4 Server-side custom configuration (optional)
@Configuration(proxyBeanMethods = false)
public class MqttServerCustomizerConfiguration {
@Bean
public MqttServerCustomizer activeRecordPluginCustomizer() {
return new MqttServerCustomizer() {
@Override
public void customize(MqttServerCreator creator) {
// 此处可自定义配置 creator,会覆盖 yml 中的配置
System.out.println("----------------MqttServerCustomizer-----------------");
}
};
}
}
5.5 MqttServerTemplate usage example
import net.dreamlu.iot.mqtt.codec.MqttQoS;
import net.dreamlu.iot.mqtt.spring.server.MqttServerTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.nio.ByteBuffer;
/**
* @author wsq
*/
@Service
public class ServerService {
@Autowired
private MqttServerTemplate server;
public boolean publish(String body) {
server.publishAll("/test/123", ByteBuffer.wrap(body.getBytes()));
return true;
}
}
5.6 Cluster processing based on mq message broadcast
- Realize
IMqttConnectStatusListener
processing equipment state storage. - Realize that
IMqttMessageListener
the message to mq, and the business processes the mq message on demand. - Implement
IMqttMessageStore
store wills and retention messages. - Implement
AbstractMqttMessageDispatcher
send the message to mq, mq broadcasts back to the mqtt cluster, and mqtt sends the message to the device. - Business messages are sent to mq, mq is broadcast to mqtt clusters, and mqtt sends messages to devices.
5.7 Prometheus + Grafana monitoring and docking
Thanks t-IO good design, monitoring indicators direct docking t-IO STAT , currently supports the following indicators, the latter will continue to improve.
Supported indicators | instruction |
---|---|
mqtt_connections_accepted | Total number of connections accepted |
mqtt_connections_closed | Number of closed connections |
mqtt_connections_size | Current connections |
mqtt_messages_handled_packets | Number of messages processed |
mqtt_messages_handled_bytes | Number of message bytes processed |
mqtt_messages_received_packets | Number of messages received |
mqtt_messages_received_bytes | Number of message bytes processed |
mqtt_messages_send_packets | Number of messages sent |
mqtt_messages_send_bytes | Number of message bytes sent |
For more information about mica-mqtt-spring-boot-starter client and other usage methods, please check the document: https://gitee.com/596392912/mica-mqtt/tree/master/mica-mqtt-spring-boot- starter
Six, common java project access
6.1 maven dependency
<dependency>
<groupId>net.dreamlu</groupId>
<artifactId>mica-mqtt-core</artifactId>
<version>1.0.2</version>
</dependency>
6.2 mica-mqtt client
// 初始化 mqtt 客户端
MqttClient client = MqttClient.create()
.ip("127.0.0.1")
.port(1883) // 默认:1883
.username("admin")
.password("123456")
.version(MqttVersion.MQTT_5) // 默认:3_1_1
.clientId("xxxxxx") // 默认:MICA-MQTT- 前缀和 36进制的纳秒数
.connect(); // 连接
// 消息订阅,同类方法 subxxx
client.subQos0("/test/#", (topic, payload) -> {
logger.info(topic + '\t' + ByteBufferUtil.toString(payload));
});
// 取消订阅
client.unSubscribe("/test/#");
// 发送消息
client.publish("/test/client", ByteBuffer.wrap("mica最牛皮".getBytes(StandardCharsets.UTF_8)));
// 断开连接
client.disconnect();
// 重连
client.reconnect();
// 停止
client.stop();
6.3 mica-mqtt server
// 注意:为了能接受更多链接(降低内存),请添加 jvm 参数 -Xss129k
MqttServer mqttServer = MqttServer.create()
// 默认:127.0.0.1
.ip("127.0.0.1")
// 默认:1883
.port(1883)
// 默认为: 8092(mqtt 默认最大消息大小),为了降低内存可以减小小此参数,如果消息过大 t-io 会尝试解析多次(建议根据实际业务情况而定)
.readBufferSize(512)
// 自定义认证
.authHandler((clientId, userName, password) -> true)
// 消息监听
.messageListener((clientId, topic, mqttQoS, payload) -> {
logger.info("clientId:{} topic:{} mqttQoS:{} message:{}", clientId, topic, mqttQoS, ByteBufferUtil.toString(payload));
})
// ssl 配置
.useSsl("", "", "")
// 自定义客户端上下线监听
.connectStatusListener(new IMqttConnectStatusListener() {
@Override
public void online(String clientId) {
}
@Override
public void offline(String clientId) {
}
})
// 自定义消息转发,可用 mq 广播实现集群化处理
.messageDispatcher(new IMqttMessageDispatcher() {
@Override
public void config(MqttServer mqttServer) {
}
@Override
public boolean send(Message message) {
return false;
}
@Override
public boolean send(String clientId, Message message) {
return false;
}
})
.debug() // 开启 t-io debug 信息日志
.start();
// 发送给某个客户端
mqttServer.publish("clientId","/test/123", ByteBuffer.wrap("mica最牛皮".getBytes()));
// 发送给所有在线监听这个 topic 的客户端
mqttServer.publishAll("/test/123", ByteBuffer.wrap("mica最牛皮".getBytes()));
// 停止服务
mqttServer.stop();
Seven, effect demonstration
8. Follow us
The above two-dimensional code scanning, more exciting content recommended every day!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。