### Initialize and Connect MQTT Client
Source: https://github.com/dromara/mica-mqtt-docs/blob/main/src/guide/android/client.md
Initialize the MqttClient with server details, authentication, and connection options. This example demonstrates synchronous connection and setting up a connection listener.
```java
// 初始化 mqtt 客户端
MqttClient client = MqttClient.create()
.ip("127.0.0.1") // mqtt 服务端 ip 地址
.port(1883) // 默认:1883
.username("admin") // 账号
.password("123456") // 密码
.version(MqttVersion.MQTT_5) // 默认:3_1_1
.clientId("xxxxxx") // 非常重要务必手动设置,一般设备 sn 号,默认:MICA-MQTT- 前缀和 36进制的纳秒数
.readBufferSize(512) // 消息一起解析的长度,默认:为 8092 (mqtt 消息最大长度)
.maxBytesInMessage(1024 * 10) // 最大包体长度,如果包体过大需要设置此参数,默认为: 10M (10*1024*1024)
.keepAliveSecs(120) // 默认:60s
.timeout(10) // 超时时间,t-io 配置,可为 null,为 null 时,t-io 默认为 5
.reconnect(true) // 是否重连,默认:true
.reInterval(5000) // 重连重试时间,reconnect 为 true 时有效,t-io 默认为:5000
.willMessage(builder -> {
builder.topic("/test/offline").messageText("down"); // 遗嘱消息
})
.connectListener(new IMqttClientConnectListener() {
@Override
public void onConnected(ChannelContext context, boolean isReconnect) {
logger.info("链接服务器成功...");
}
@Override
public void onDisconnect(ChannelContext channelContext, Throwable throwable, String remark, boolean isRemove) {
logger.info("与链接服务器断开连接...");
}
})
.properties() // mqtt5 properties
.connectSync(); // 同步连接,也可以使用 connect(),可以避免 broker 没启动照成启动卡住。
```
--------------------------------
### MQTT.js WebSocket Connection Example
Source: https://github.com/dromara/mica-mqtt-docs/blob/main/src/faq/faq.md
Connect to an MQTT broker using MQTT.js over WebSocket. This example demonstrates client configuration, including host, port, and connection options like keepalive, clientId, username, and password. It also includes basic error and reconnect event handling.
```javascript
const clientId = 'mqttjs_' + Math.random().toString(16).substr(2, 8)
const host = 'ws://mqtt.dreamlu.net:8083/mqtt'
const options = {
keepalive: 60,
clientId: clientId,
username: 'mqtt登录用户名',
password: 'mqtt登录密码',
protocolId: 'MQTT',
protocolVersion: 4,
clean: true,
reconnectPeriod: 1000,
connectTimeout: 30 * 1000,
will: {
topic: 'WillMsg',
payload: 'Connection Closed abnormally..!',
qos: 0,
retain: false
},
}
console.log('Connecting mqtt client')
const client = mqtt.connect(host, options)
client.on('error', (err) => {
console.log('Connection error: ', err)
client.end()
})
client.on('reconnect', () => {
console.log('Reconnecting...')
})
```
--------------------------------
### Add MQTT Subscription After JFinal Start
Source: https://github.com/dromara/mica-mqtt-docs/blob/main/src/guide/jfinal/client.md
Subscribe to MQTT topics after the JFinal application has started using MqttClientKit. Ensure the listener is obtained via Aop.
```java
@Override
public void onStart() {
IMqttClientMessageListener clientMessageListener = Aop.get(TestMqttClientMessageListener.class);
MqttClientKit.subQos0("#", clientMessageListener);
}
```
--------------------------------
### MQTT Client Configuration Example
Source: https://github.com/dromara/mica-mqtt-docs/blob/main/src/guide/solon/client.md
This YAML configuration demonstrates various options for setting up the MQTT client, including connection details, authentication, and advanced settings like SSL and thread pool sizes. Ensure 'clientId' is unique for each device.
```yaml
mqtt:
client:
enabled: true # 是否开启客户端,默认:true
ip: 127.0.0.1 # 连接的服务端 ip ,默认:127.0.0.1
port: 1883 # 端口:默认:1883
name: Mica-Mqtt-Client # 名称,默认:Mica-Mqtt-Client
clientId: 000001 # 客户端Id(非常重要,一般为设备 sn,不可重复)
username: mica # 认证的用户名,注意:2.5.x 之前是 user-name
password: 123456 # 认证的密码
timeout: 5 # 超时时间,单位:秒,默认:5秒
reconnect: true # 是否重连,默认:true
re-interval: 5000 # 重连时间,默认 5000 毫秒
version: mqtt_3_1_1 # mqtt 协议版本,可选 MQTT_3_1、mqtt_3_1_1、mqtt_5,默认:mqtt_3_1_1
read-buffer-size: 8KB # 接收数据的 buffer size,默认:8k
max-bytes-in-message: 10MB # 消息解析最大 bytes 长度,默认:10M
buffer-allocator: heap # 堆内存和堆外内存,默认:堆内存
keep-alive-secs: 60 # keep-alive 时间,单位:秒
heartbeat-mode: LAST_REQ # 心跳模式,支持最后发送或接收心跳时间来计算心跳,默认:最后发送心跳的时间。(2.4.3 开始支持)
heartbeat-timeout-strategy: PING # 心跳超时策略,支持发送 PING 和 CLOSE 断开连接,默认:最大努力发送 PING。(2.4.3 开始支持)
clean-start: true # session 保留 2.5.x 使用 clean-start,老版本用 clean-session,默认:true
session-expiry-interval-secs: 0 # 开启保留 session 时,session 的有效期,默认:0(2.4.2 开始支持)
group-executor-size: 8 # AIO AsynchronousChannelGroup 的线程池,默认:2。(2.5.12 开始支持)
tio-executor-size: 8 # tio 编解码等线程数,默认:3,如果消息量比较大,处理较慢,例如做 emqx 的转发消息处理,可以调大此参数(2.5.12 开始支持)
mqtt-executor-size: 8 # mqtt 业务线程数,默认:2或CPU核心数,如果消息量比较大,处理较慢,例如做 emqx 的转发消息处理,可以调大此参数(取较大值)(2.5.12 开始支持)
biz-thread-pool-size: 2 # 同 mqtt-executor-size(2.4.2 开始支持,2.5.12 已经弃用)
ssl:
enabled: false # 是否开启 ssl 认证,2.1.0 开始支持双向认证
keystore-path: # 可选参数:ssl 双向认证 keystore 目录,支持 classpath:/ 路径。
keystore-pass: # 可选参数:ssl 双向认证 keystore 密码
truststore-path: # 可选参数:ssl 双向认证 truststore 目录,支持 classpath:/ 路径。
truststore-pass: # 可选参数:ssl 双向认证 truststore 密码
```
--------------------------------
### Initialize MqttServer (2.5.x+)
Source: https://github.com/dromara/mica-mqtt-docs/blob/main/src/guide/android/server.md
Initialize the MqttServer with custom configurations for buffer size, message listeners, connection status, interceptors, WebSocket, and HTTP API. This version supports starting and scheduling messages.
```java
// 注意:为了能接受更多链接(降低内存),请添加 jvm 参数 -Xss129k
MqttServer mqttServer = MqttServer.create()
// 服务端 ip 默认为空,0.0.0.0,建议不要设置,端口 默认:1883
.enableMqtt(1883)
// 默认为: 8192(mqtt 默认最大消息大小),为了降低内存可以减小小此参数,如果消息过大 t-io 会尝试解析多次(建议根据实际业务情况而定)
.readBufferSize(8192)
// 最大包体长度
// .maxBytesInMessage(1024 * 100)
// mqtt 3.1 协议会校验 clientId 长度。
// .maxClientIdLength(64)
.messageListener((context, clientId, topic, qos, message) -> {
logger.info("clientId:{} payload:{}", clientId, new String(message.payload(), StandardCharsets.UTF_8));
})
// 客户端连接状态监听
.connectStatusListener(new MqttConnectStatusListener())
// 自定义消息拦截器
.addInterceptor(new MqttMessageInterceptor())
// 开启 websocket
.enableMqttWs()
// 开启 mqtt http 接口
.enableMqttHttpApi(builder ->
builder
.basicAuth("mica", "mica") // http basic 认证
.mcpServer() // 开启 mcp 服务
.build()
)
// 开始 stat 监控
.statEnable()
// 开启 debug 信息日志
.debug()
.start();
// 定时下发消息
mqttServer.schedule(() -> {
String message = "mica最牛皮 " + System.currentTimeMillis();
mqttServer.publishAll("/test/123", message.getBytes(StandardCharsets.UTF_8));
}, 2000);
// 2.3.2 开始支持 stop 关闭
// mqttServer.stop();
```
--------------------------------
### Get All API Endpoints
Source: https://github.com/dromara/mica-mqtt-docs/blob/main/src/guide/httpApi.md
Use this endpoint to retrieve a list of all available API endpoints. Requires basic authentication.
```bash
$ curl -i --basic -u mica:mica "http://localhost:18083/api/v1/endpoints"
{
"data": [
{
"method": "GET",
"path": "/api/v1/endpoints"
},
{
"method": "GET",
"path": "/api/v1/clients"
},
{
"method": "POST",
"path": "/api/v1/mqtt/unsubscribe"
},
{
"method": "GET",
"path": "/api/v1/clients/info"
},
{
"method": "GET",
"path": "/api/v1/stats"
},
{
"method": "POST",
"path": "/api/v1/mqtt/publish/batch"
},
{
"method": "POST",
"path": "/api/v1/mqtt/subscribe/batch"
},
{
"method": "GET",
"path": "/api/v1/client/subscriptions"
},
{
"method": "POST",
"path": "/api/v1/mqtt/publish"
},
{
"method": "POST",
"path": "/api/v1/mqtt/unsubscribe/batch"
},
{
"method": "POST",
"path": "/api/v1/mqtt/subscribe"
},
{
"method": "POST",
"path": "/api/v1/clients/delete"
}
],
"code": 1
}
```
--------------------------------
### Subscribe to MQTT Topic
Source: https://github.com/dromara/mica-mqtt-docs/blob/main/src/guide/httpApi.md
Subscribe to one or more MQTT topics. Requires basic authentication and a JSON payload with topic, clientId, and optional qos. This example shows subscribing to a single topic.
```bash
$ curl -i --basic -u mica:mica -X POST "http://localhost:18083/api/v1/mqtt/subscribe" -d '{"topic":"a/b/c","qos":1,"clientId":"example"}'
{"code":1}
```
--------------------------------
### Client Message Subscription Callback
Source: https://github.com/dromara/mica-mqtt-docs/blob/main/src/version/update.md
Example of subscribing to messages with updated callback parameters including context, topic, message, and payload. Use this for handling incoming MQTT messages on the client side.
```java
client.subQos0("/test/#", (context, topic, message, payload) -> {
logger.info(topic + '\t' + ByteBufferUtil.toString(payload));
});
```
--------------------------------
### Get Client Details
Source: https://github.com/dromara/mica-mqtt-docs/blob/main/src/guide/httpApi.md
Retrieve detailed information about a specific MQTT client using its clientId. Returns connection status, timestamps, and protocol details.
```bash
$ curl -i --basic -u mica:mica -X POST "http://localhost:18083/api/v1/clients/info?clientId=mqttx_5fe4cfcf"
{"code":1,"data":{"clientId":"mqttx_5fe4cfcf","connected":true,"connectedAt":1681792417835,"createdAt":1681792417835,"ipAddress":"127.0.0.1","port":11852,"protoName":"MQTT","protoVer":5}}
```
--------------------------------
### Get Client Details
Source: https://github.com/dromara/mica-mqtt-docs/blob/main/src/guide/httpApi.md
Retrieves detailed information about a specific MQTT client using its client ID.
```APIDOC
## GET /api/v1/clients/info
### Description
Retrieves detailed information for a given client ID.
### Method
GET
### Endpoint
/api/v1/clients/info
### Parameters
#### Query Parameters
- **clientId** (String) - Required - The unique identifier of the client.
### Response
#### Success Response (200)
- **code** (Integer) - Indicates the result of the operation. 0 typically signifies success.
- **clientId** (String) - The client's unique identifier.
- **username** (String) - The username associated with the client.
- **connected** (Boolean) - Indicates whether the client is currently connected.
- **createdAt** (Long) - The timestamp when the client was created.
- **connectedAt** (Long) - The timestamp when the client successfully connected.
```
--------------------------------
### Initialize and Use MqttClient
Source: https://github.com/dromara/mica-mqtt-docs/blob/main/src/guide/java/client.md
Demonstrates initializing an MQTT client with custom configurations, subscribing to topics, publishing messages, and managing the connection lifecycle. Ensure a unique clientId is set for proper device identification.
```java
// Initialize mqtt client
MqttClient client = MqttClient.create()
.ip("127.0.0.1") // mqtt server ip address
.port(1883) // default: 1883
.username("admin") // username
.password("123456") // password
.version(MqttVersion.MQTT_5) // default: 3_1_1
.clientId("xxxxxx") // very important, must be set manually, usually device sn, default: MICA-MQTT- prefix and 36-bit nanosecond
.readBufferSize(512) // message parsing length, default: 8092 (max mqtt message length)
.maxBytesInMessage(1024 * 10) // max payload length, set this if payload is too large, default: 10M (10*1024*1024)
.keepAliveSecs(120) // default: 60s
.timeout(10) // timeout, t-io configuration, can be null, if null, t-io defaults to 5
.reconnect(true) // whether to reconnect, default: true
.reInterval(5000) // reconnect retry interval, valid when reconnect is true, t-io default: 5000
.willMessage(builder -> {
builder.topic("/test/offline").messageText("down"); // will message
})
.connectListener(new IMqttClientConnectListener() {
@Override
public void onConnected(ChannelContext context, boolean isReconnect) {
logger.info("Successfully connected to the server...");
}
@Override
public void onDisconnect(ChannelContext channelContext, Throwable throwable, String remark, boolean isRemove) {
logger.info("Disconnected from the server...");
}
})
.properties() // mqtt5 properties
.connectSync(); // synchronous connection, can also use connect(), which avoids blocking startup if broker is not started.
// Subscribe to messages, similar to subxxx methods
client.subQos0("/test/#", (context, topic, message, payload) -> {
logger.info(topic + '\t' + new String(payload, StandardCharsets.UTF_8));
});
// Unsubscribe
client.unSubscribe("/test/#");
// Send message
client.publish("/test/client", "mica is the best".getBytes(StandardCharsets.UTF_8));
// Disconnect
client.disconnect();
// Reconnect
client.reconnect();
// Stop
client.stop();
```
--------------------------------
### Get All API Endpoints
Source: https://github.com/dromara/mica-mqtt-docs/blob/main/src/guide/httpApi.md
Retrieves a list of all available API endpoints.
```APIDOC
## GET /api/v1/endpoints
### Description
Retrieves a list of all available API endpoints.
### Method
GET
### Endpoint
/api/v1/endpoints
### Response
#### Success Response (200)
- **code** (Integer) - Indicates the success of the operation. Should be 1 for success.
- **data** (Array) - A list of API endpoints.
- Each item in the array is an object with:
- **method** (String) - The HTTP method of the endpoint.
- **path** (String) - The path of the endpoint.
### Request Example
```bash
$ curl -i --basic -u mica:mica "http://localhost:18083/api/v1/endpoints"
```
### Response Example
```json
{
"data": [
{
"method": "GET",
"path": "/api/v1/endpoints"
},
{
"method": "GET",
"path": "/api/v1/clients"
}
],
"code": 1
}
```
```
--------------------------------
### Initialize MqttServer (2.4.x and below)
Source: https://github.com/dromara/mica-mqtt-docs/blob/main/src/guide/android/server.md
Initialize the MqttServer with configurations for IP, port, buffer size, message size, authentication, message listeners, heartbeat timeout, SSL, proxy protocol, and client status. This version supports publishing messages to specific clients or all clients.
```java
// 注意:为了能接受更多链接(降低内存),请添加 jvm 参数 -Xss129k
MqttServer mqttServer = MqttServer.create()
// 服务端 ip 默认为空,0.0.0.0,建议不要设置
.ip("0.0.0.0")
// 默认:1883
.port(1883)
// 默认为: 8092(mqtt 默认最大消息大小),为了降低内存可以减小小此参数,如果消息过大 t-io 会尝试解析多次(建议根据实际业务情况而定)
.readBufferSize(512)
// 最大包体长度,如果包体过大需要设置此参数,默认为: 8092
.maxBytesInMessage(1024 * 100)
// 自定义认证
.authHandler((clientId, userName, password) -> true)
// 消息监听
.messageListener((context, clientId, message) -> {
logger.info("clientId:{} message:{} payload:{}", clientId, message, new String(message.getPayload(), StandardCharsets.UTF_8));
})
// 心跳超时时间,默认:120s
.heartbeatTimeout(120_1000L)
// ssl 配置
.useSsl("", "", "")
// 开启代理协议,支持 nginx 开启 tcp proxy_protocol on; 时转发源 ip 信息。2.4.1 版本开始支持
.proxyProtocolEnable()
// 自定义客户端上下线监听
.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;
}
})
.start();
// 发送给某个客户端
mqttServer.publish("clientId","/test/123", "mica最牛皮".getBytes(StandardCharsets.UTF_8));
// 发送给所有在线监听这个 topic 的客户端
mqttServer.publishAll("/test/123", "mica最牛皮".getBytes(StandardCharsets.UTF_8));
// 停止服务
mqttServer.stop();
```
--------------------------------
### Configure Mica MQTT Server (2.5.x+)
Source: https://github.com/dromara/mica-mqtt-docs/blob/main/src/guide/java/server.md
Set up the MQTT server with custom configurations for ports, buffer sizes, message listeners, and optional features like WebSocket and HTTP API. Ensure JVM parameter -Xss129k is set for handling more connections.
```java
// 注意:为了能接受更多链接(降低内存),请添加 jvm 参数 -Xss129k
MqttServer mqttServer = MqttServer.create()
// 服务端 ip 默认为空,0.0.0.0,建议不要设置,端口 默认:1883
.enableMqtt(1883)
// 默认为: 8192(mqtt 默认最大消息大小),为了降低内存可以减小小此参数,如果消息过大 t-io 会尝试解析多次(建议根据实际业务情况而定)
.readBufferSize(8192)
// 最大包体长度
// .maxBytesInMessage(1024 * 100)
// mqtt 3.1 协议会校验 clientId 长度。
// .maxClientIdLength(64)
.messageListener((context, clientId, topic, qos, message) -> {
logger.info("clientId:{} payload:{}", clientId, new String(message.payload(), StandardCharsets.UTF_8));
})
// 客户端连接状态监听
.connectStatusListener(new MqttConnectStatusListener())
// 自定义消息拦截器
.addInterceptor(new MqttMessageInterceptor())
// 开启 websocket
.enableMqttWs()
// 开启 mqtt http 接口
.enableMqttHttpApi(builder ->
builder
.basicAuth("mica", "mica") // http basic 认证
.mcpServer() // 开启 mcp 服务
.build()
)
// 开始 stat 监控
.statEnable()
// 开启 debug 信息日志
.debug()
.start();
// 定时下发消息
mqttServer.schedule(() -> {
String message = "mica最牛皮 " + System.currentTimeMillis();
mqttServer.publishAll("/test/123", message.getBytes(StandardCharsets.UTF_8));
}, 2000);
// 2.3.2 开始支持 stop 关闭
// mqttServer.stop();
```
--------------------------------
### Configure Mica MQTT Server (2.4.x and below)
Source: https://github.com/dromara/mica-mqtt-docs/blob/main/src/guide/java/server.md
Set up the MQTT server with configurations for IP, port, buffer sizes, message listeners, heartbeat timeouts, SSL, and proxy protocol. This version also supports custom authentication and message dispatchers.
```java
// 注意:为了能接受更多链接(降低内存),请添加 jvm 参数 -Xss129k
MqttServer mqttServer = MqttServer.create()
// 服务端 ip 默认为空,0.0.0.0,建议不要设置
.ip("0.0.0.0")
// 默认:1883
.port(1883)
// 默认为: 8092(mqtt 默认最大消息大小),为了降低内存可以减小小此参数,如果消息过大 t-io 会尝试解析多次(建议根据实际业务情况而定)
.readBufferSize(512)
// 最大包体长度,如果包体过大需要设置此参数,默认为: 8092
.maxBytesInMessage(1024 * 100)
// 自定义认证
.authHandler((clientId, userName, password) -> true)
// 消息监听
.messageListener((context, clientId, message) -> {
logger.info("clientId:{} message:{} payload:{}", clientId, message, new String(message.getPayload(), StandardCharsets.UTF_8));
})
// 心跳超时时间,默认:120s
.heartbeatTimeout(120_1000L)
// ssl 配置
.useSsl("", "", "")
// 开启代理协议,支持 nginx 开启 tcp proxy_protocol on; 时转发源 ip 信息。2.4.1 版本开始支持
.proxyProtocolEnable()
// 自定义客户端上下线监听
.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() // 开启 debug 信息日志
.start();
// 发送给某个客户端
mqttServer.publish("clientId","/test/123", "mica最牛皮".getBytes(StandardCharsets.UTF_8));
// 发送给所有在线监听这个 topic 的客户端
mqttServer.publishAll("/test/123", "mica最牛皮".getBytes(StandardCharsets.UTF_8));
// 停止服务
mqttServer.stop();
```
--------------------------------
### Add Dependency
Source: https://github.com/dromara/mica-mqtt-docs/blob/main/src/guide/solon/server.md
Include this dependency in your project's pom.xml to use the mica-mqtt-server-solon-plugin.
```xml
org.dromara.mica-mqtt
mica-mqtt-server-solon-plugin
${version}
```
--------------------------------
### MQTT Server Configuration (2.5.x+)
Source: https://github.com/dromara/mica-mqtt-docs/blob/main/src/guide/solon/server.md
Configure the MQTT server settings, including enabled status, name, timeouts, buffer sizes, authentication, and various listeners (MQTT, SSL, WebSocket, WSS, HTTP).
```yaml
mqtt:
server:
enabled: true # 是否开启服务端,默认:true
name: Mica-Mqtt-Server # 名称,默认:Mica-Mqtt-Server
heartbeat-timeout: 120000 # 心跳超时,单位毫秒,默认: 1000 * 120
read-buffer-size: 8KB # 接收数据的 buffer size,默认:8k
max-bytes-in-message: 10MB # 消息解析最大 bytes 长度,默认:10M
auth:
enable: false # 是否开启 mqtt 认证
username: mica # mqtt 认证用户名
password: mica # mqtt 认证密码
debug: true # 如果开启 prometheus 指标收集建议关闭
stat-enable: true # 开启指标收集,debug 和 prometheus 开启时需要打开,默认开启,关闭节省内存
mqtt-listener: # mqtt 监听器
enable: true # 是否开启,默认:false
# ip: "0.0.0.0" # 服务端 ip 默认为空,0.0.0.0,建议不要设置
port: 1883 # 端口,默认:1883
mqtt-ssl-listener: # mqtt ssl 监听器
enable: false # 是否开启,默认:false
port: 8883 # 端口,默认:8883
ssl: # ssl 配置,必须
keystore-path: # 必须参数:ssl keystore 目录,支持 classpath:/ 路径。
keystore-pass: # 必选参数:ssl keystore 密码
truststore-path: # 可选参数:ssl 双向认证 truststore 目录,支持 classpath:/ 路径。
truststore-pass: # 可选参数:ssl 双向认证 truststore 密码
client-auth: none # 是否需要客户端认证(双向认证),默认:NONE(不需要)
ws-listener: # websocket mqtt 监听器
enable: true # 是否开启,默认:false
port: 8083 # websocket 端口,默认:8083
wss-listener: # websocket ssl mqtt 监听器
enable: false # 是否开启,默认:false
port: 8084 # 端口,默认:8084
ssl: # ssl 配置,必须
keystore-path: # 必须参数:ssl keystore 目录,支持 classpath:/ 路径。
keystore-pass: # 必选参数:ssl keystore 密码
truststore-path: # 可选参数:ssl 双向认证 truststore 目录,支持 classpath:/ 路径。
truststore-pass: # 可选参数:ssl 双向认证 truststore 密码
client-auth: none # 是否需要客户端认证(双向认证),默认:NONE(不需要)
http-listener:
enable: true
port: 18083
basic-auth: # 基础认证
enable: true
username: mica
password: mica
mcp-server: # 大模型 mcp
enable: true
```
--------------------------------
### Batch Subscribe to MQTT Topics
Source: https://github.com/dromara/mica-mqtt-docs/blob/main/src/guide/httpApi.md
Subscribe to multiple MQTT topics simultaneously. Specify the topic, clientId, and optional QoS for each subscription.
```bash
$ curl -i --basic -u mica:mica -X POST "http://localhost:18083/api/v1/mqtt/subscribe/batch" -d '[{"topic":"a","qos":1,"clientId":"example"},{"topic":"b","qos":1,"clientId":"example"},{"topic":"c","qos":1,"clientId":"example"}]'
{"code":1}
```
--------------------------------
### Configure MqttServerPlugin (2.5.x+)
Source: https://github.com/dromara/mica-mqtt-docs/blob/main/src/guide/jfinal/server.md
Configure the MqttServerPlugin for JFinal versions 2.5.x and above, enabling MQTT on port 1883 and MQTT WebSocket.
```java
MqttServerPlugin plugin = new MqttServerPlugin();
plugin.config(mqttServerCreator -> {
// mqttServerCreator 上有很多方法,详见 mica-mqtt-core
mqttServerCreator.enableMqtt(1883).enableMqttWs();
});
```
--------------------------------
### Configure MqttServerPlugin (2.4.x-)
Source: https://github.com/dromara/mica-mqtt-docs/blob/main/src/guide/jfinal/server.md
Configure the MqttServerPlugin for JFinal versions 2.4.x and below, specifying MQTT and WebSocket ports.
```java
MqttServerPlugin plugin = new MqttServerPlugin();
plugin.config(mqttServerCreator -> {
// mqttServerCreator 上有很多方法,详见 mica-mqtt-core
mqttServerCreator.port(1883).webPort(8083).websocketEnable(true);
});
```
--------------------------------
### Batch Subscribe to MQTT Topics
Source: https://github.com/dromara/mica-mqtt-docs/blob/main/src/guide/httpApi.md
Allows for batch subscription to multiple MQTT topics. Each subscription can specify a topic, client ID, and QoS level.
```APIDOC
## POST /api/v1/mqtt/subscribe/batch
### Description
Subscribes to multiple MQTT topics in a batch.
### Method
POST
### Endpoint
/api/v1/mqtt/subscribe/batch
### Parameters
#### Request Body
- **topic** (String) - Required - The MQTT topic to subscribe to.
- **clientId** (String) - Required - The identifier of the client.
- **qos** (Integer) - Optional - The Quality of Service level for the subscription. Defaults to 0.
### Request Example
```json
[
{
"topic": "a",
"qos": 1,
"clientId": "example"
},
{
"topic": "b",
"qos": 1,
"clientId": "example"
},
{
"topic": "c",
"qos": 1,
"clientId": "example"
}
]
```
### Response
#### Success Response (200)
- **code** (Integer) - Indicates the result of the operation. 0 typically signifies success.
```
--------------------------------
### Configure mica-mqtt Client Plugin in JFinal Config
Source: https://github.com/dromara/mica-mqtt-docs/blob/main/src/guide/jfinal/client.md
Configure and add the MqttClientPlugin in your JFinal Config's configPlugin method. Set MQTT connection details and a connect listener.
```java
MqttClientPlugin mqttClientPlugin = new MqttClientPlugin();
mqttClientPlugin.config(mqttClientCreator -> {
// 设置 mqtt 连接配置信息
mqttClientCreator
.clientId("clientId") // 按需配置,相同的会互踢
.ip("mqtt.dreamlu.net")
.port(1883)
.connectListener(Aop.get(MqttClientConnectListener.class));
});
me.add(mqttClientPlugin);
```
--------------------------------
### Configure Maven Mirror in settings.xml
Source: https://github.com/dromara/mica-mqtt-docs/blob/main/src/faq/faq.md
Configure Tencent's mirror repository in your .m2/settings.xml file to improve Maven package download speeds. This method is useful if your development tool allows selecting a specific settings.xml file.
```xml
central
https://mirrors.cloud.tencent.com/nexus/repository/maven-public/
central
```
--------------------------------
### MQTT Server Configuration (2.4.x-)
Source: https://github.com/dromara/mica-mqtt-docs/blob/main/src/guide/solon/server.md
Configure the MQTT server settings for versions prior to 2.5.x, including enabled status, ports, buffer allocation, timeouts, authentication, and SSL options.
```yaml
mqtt:
server:
enabled: true # 是否开启服务端,默认:true
# ip: 0.0.0.0 # 服务端 ip 默认为空,0.0.0.0,建议不要设置
port: 1883 # 端口,默认:1883
name: Mica-Mqtt-Server # 名称,默认:Mica-Mqtt-Server
buffer-allocator: HEAP # 堆内存和堆外内存,默认:堆内存
heartbeat-timeout: 120000 # 心跳超时,单位毫秒,默认: 1000 * 120
read-buffer-size: 8KB # 接收数据的 buffer size,默认:8k
max-bytes-in-message: 10MB # 消息解析最大 bytes 长度,默认:10M
auth:
enable: false # 是否开启 mqtt 认证
username: mica # mqtt 认证用户名
password: mica # mqtt 认证密码
debug: true # 如果开启 prometheus 指标收集建议关闭
stat-enable: true # 开启指标收集,debug 和 prometheus 开启时需要打开,默认开启,关闭节省内存
proxy-protocol-enable: false # 代理协议支持,nginx 可开启 tcp proxy_protocol on; 时转发源 ip 信息。2.4.1 版本开始支持
web-port: 8083 # http、websocket 端口,默认:8083
websocket-enable: true # 是否开启 websocket,默认: true
http-enable: false # 是否开启 http api,默认: false
http-basic-auth:
enable: false # 是否开启 http basic auth,默认: false
username: mica # http basic auth 用户名
password: mica # http basic auth 密码
ssl: # mqtt tcp ssl 认证
enabled: false # 是否开启 ssl 认证,2.1.0 开始支持双向认证
keystore-path: # 必须参数:ssl keystore 目录,支持 classpath:/ 路径。
keystore-pass: # 必选参数:ssl keystore 密码
truststore-path: # 可选参数:ssl 双向认证 truststore 目录,支持 classpath:/ 路径。
truststore-pass: # 可选参数:ssl 双向认证 truststore 密码
client-auth: none # 是否需要客户端认证(双向认证),默认:NONE(不需要)
```
--------------------------------
### Add mica-mqtt-client-solon-plugin Dependency
Source: https://github.com/dromara/mica-mqtt-docs/blob/main/src/guide/solon/client.md
Include this XML snippet in your Maven project's pom.xml to add the MQTT client plugin dependency.
```xml
org.dromara.mica-mqtt
mica-mqtt-client-solon-plugin
${version}
```
--------------------------------
### Add mica-mqtt Client Dependency
Source: https://github.com/dromara/mica-mqtt-docs/blob/main/src/guide/spring/client.md
Include this Maven dependency to add the mica-mqtt client starter to your Spring Boot project.
```xml
org.dromara.mica-mqtt
mica-mqtt-client-spring-boot-starter
${最新版本}
```
--------------------------------
### Configure Maven Repository in pom.xml
Source: https://github.com/dromara/mica-mqtt-docs/blob/main/src/faq/faq.md
Add Tencent's mirror repository to your project's pom.xml to accelerate Maven package downloads. This is particularly useful for fetching the latest mica-mqtt packages.
```xml
4.0.0
central
https://mirrors.cloud.tencent.com/nexus/repository/maven-public/
false
```
--------------------------------
### Client SSL Configuration
Source: https://github.com/dromara/mica-mqtt-docs/blob/main/src/version/update.md
Configuration properties for enabling and setting up SSL/TLS for the MQTT client. This includes enabling SSL, and optionally providing keystore and truststore paths and passwords for mutual TLS authentication.
```yaml
mica:
client:
ssl:
enabled: false # 是否开启 ssl 认证,2.1.0 开始支持双向认证
keystore-path: # 可选参数:ssl 双向认证 keystore 目录,支持 classpath:/ 路径。
keystore-pass: # 可选参数:ssl 双向认证 keystore 密码
truststore-path: # 可选参数:ssl 双向认证 truststore 目录,支持 classpath:/ 路径。
truststore-pass: # 可选参数:ssl 双向认证 truststore 密码
```
--------------------------------
### Server SSL Configuration
Source: https://github.com/dromara/mica-mqtt-docs/blob/main/src/version/update.md
Configuration properties for enabling and setting up SSL/TLS for the MQTT server. This includes enabling SSL, providing keystore details, and configuring client authentication for mutual TLS.
```yaml
mica:
server:
ssl: # mqtt tcp ssl 认证
enabled: false # 是否开启 ssl 认证,2.1.0 开始支持双向认证
keystore-path: # 必须参数:ssl keystore 目录,支持 classpath:/ 路径。
keystore-pass: # 必选参数:ssl keystore 密码
truststore-path: # 可选参数:ssl 双向认证 truststore 目录,支持 classpath:/ 路径。
truststore-pass: # 可选参数:ssl 双向认证 truststore 密码
client-auth: none # 是否需要客户端认证(双向认证),默认:NONE(不需要)
```
--------------------------------
### Custom Java Configuration for MQTT Client
Source: https://github.com/dromara/mica-mqtt-docs/blob/main/src/guide/spring/client.md
Provide a custom `MqttClientCustomizer` bean to programmatically configure the `MqttClientCreator`. This allows overriding settings defined in the YAML configuration.
```java
@Configuration(proxyBeanMethods = false)
public class MqttClientCustomizerConfiguration {
@Bean
public MqttClientCustomizer mqttClientCustomizer() {
return new MqttClientCustomizer() {
@Override
public void customize(MqttClientCreator creator) {
// 此处可自定义配置 creator,会覆盖 yml 中的配置
System.out.println("----------------MqttServerCustomizer-----------------");
}
};
}
}
```
--------------------------------
### Add mica-mqtt Server JFinal Plugin Dependency
Source: https://github.com/dromara/mica-mqtt-docs/blob/main/src/guide/jfinal/server.md
Include this dependency in your project's pom.xml to use the mica-mqtt server JFinal plugin.
```xml
org.dromara.mica-mqtt
mica-mqtt-server-jfinal-plugin
${最新版本}
```
--------------------------------
### Add mica-mqtt-client Dependency
Source: https://github.com/dromara/mica-mqtt-docs/blob/main/src/guide/java/client.md
Include this XML snippet in your Maven project's pom.xml to add the mica-mqtt-client library.
```xml
org.dromara.mica-mqtt
mica-mqtt-client
${mica-mqtt.version}
```