first commit

This commit is contained in:
zc
2025-12-08 10:40:43 +08:00
commit 871ae8be0a
410 changed files with 38212 additions and 0 deletions

View File

@@ -0,0 +1,6 @@
## SpringBoot + mica-mqtt-client 应用演示
## 启动步骤
1. 先启动 mica-mqtt-server-spring-boot-example
2. 再启动 mica-mqtt-client-spring-boot-example

View File

@@ -0,0 +1,62 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>mica-mqtt-client-spring-boot-example</artifactId>
<name>${project.artifactId}</name>
<url>https://www.dreamlu.net</url>
<parent>
<groupId>org.dromara.mica-mqtt</groupId>
<artifactId>example</artifactId>
<version>${revision}</version>
</parent>
<dependencies>
<dependency>
<groupId>org.dromara.mica-mqtt</groupId>
<artifactId>mica-mqtt-client-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>net.dreamlu</groupId>
<artifactId>mica-lite</artifactId>
</dependency>
<dependency>
<groupId>net.dreamlu</groupId>
<artifactId>mica-logging</artifactId>
</dependency>
<dependency>
<groupId>net.dreamlu</groupId>
<artifactId>mica-openapi</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring.boot.version}</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,21 @@
package org.dromara.mica.mqtt.client;
import org.dromara.mica.mqtt.spring.client.annotation.EnableMqttClients;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author wsq
*/
@SpringBootApplication
@EnableMqttClients
public class MqttClientApplication {
/**
* 先启动 mica-mqtt-server-spring-boot-example 再启动本项目,进行测试
*/
public static void main(String[] args) {
SpringApplication.run(MqttClientApplication.class, args);
}
}

View File

@@ -0,0 +1,31 @@
package org.dromara.mica.mqtt.client.config;
import org.dromara.mica.mqtt.core.client.DefaultMqttClientSession;
import org.dromara.mica.mqtt.core.client.MqttClientCreator;
import org.dromara.mica.mqtt.spring.client.MqttClientTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 示例多个 mqtt client
*
* @author L.cm
*/
@Configuration
public class OtherMqttClientConfiguration {
@Bean("mqttClientTemplate1")
public MqttClientTemplate mqttClientTemplate1() {
// 基于 clientCreator 的配置构建一个新的
MqttClientCreator mqttClientCreator1 = new MqttClientCreator()
// 修改不同的配置
// .ip("mqtt.dreamlu.net")
.port(1884)
.username("mica")
.password("mica")
// 避免 client session 冲突
.clientSession(new DefaultMqttClientSession());
return new MqttClientTemplate(mqttClientCreator1);
}
}

View File

@@ -0,0 +1,32 @@
package org.dromara.mica.mqtt.client.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.dromara.mica.mqtt.client.service.ClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@Tag(name = "Mqtt::客户端")
@RequestMapping("/mqtt/client")
@RestController
public class ClientController {
@Autowired
private ClientService service;
@Operation(summary = "publish")
@PostMapping("/publish")
public boolean publish(@RequestBody String body) {
service.publish(body);
service.publishHelloInterfaceA(body);
service.publishHelloInterfaceB(body);
return true;
}
@Operation(summary = "sub")
@GetMapping("/sub")
public boolean sub() {
return service.sub();
}
}

View File

@@ -0,0 +1,53 @@
/*
* Copyright (c) 2019-2029, Dreamlu 卢春梦 (596392912@qq.com & dreamlu.net).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dromara.mica.mqtt.client.listener;
import lombok.extern.slf4j.Slf4j;
import org.dromara.mica.mqtt.core.client.MqttClientCreator;
import org.dromara.mica.mqtt.spring.client.event.MqttConnectedEvent;
import org.dromara.mica.mqtt.spring.client.event.MqttDisconnectEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
/**
* 客户端连接状态监听
*
* @author L.cm
*/
@Slf4j
@Service
public class MqttClientConnectListener {
@Autowired
private MqttClientCreator mqttClientCreator;
@EventListener
public void onConnected(MqttConnectedEvent event) {
log.info("MqttConnectedEvent:{}", event);
}
@EventListener
public void onDisconnect(MqttDisconnectEvent event) {
log.info("MqttDisconnectEvent:{}", event);
// 在断线时更新 clientId、username、password只能改这 3 个,不可调用其他方法。
// mqttClientCreator.clientId("newClient" + System.currentTimeMillis())
// .username("newUserName")
// .password("newPassword");
}
}

View File

@@ -0,0 +1,27 @@
package org.dromara.mica.mqtt.client.listener;
import lombok.extern.slf4j.Slf4j;
import org.dromara.mica.mqtt.codec.message.MqttPublishMessage;
import org.dromara.mica.mqtt.core.client.IMqttClientMessageListener;
import org.dromara.mica.mqtt.core.annotation.MqttClientSubscribe;
import org.springframework.stereotype.Service;
import org.tio.core.ChannelContext;
import java.nio.charset.StandardCharsets;
/**
* 客户端消息监听的另一种方式
*
* @author L.cm
*/
@Slf4j
@Service
@MqttClientSubscribe("${topic1}")
public class MqttClientMessageListener implements IMqttClientMessageListener {
@Override
public void onMessage(ChannelContext context, String topic, MqttPublishMessage message, byte[] payload) {
log.info("topic:{} payload:{}", topic, new String(payload, StandardCharsets.UTF_8));
}
}

View File

@@ -0,0 +1,70 @@
package org.dromara.mica.mqtt.client.listener;
import lombok.extern.slf4j.Slf4j;
import org.dromara.mica.mqtt.client.pojo.User;
import org.dromara.mica.mqtt.codec.message.MqttPublishMessage;
import org.dromara.mica.mqtt.codec.MqttQoS;
import org.dromara.mica.mqtt.core.deserialize.MqttJsonDeserializer;
import org.dromara.mica.mqtt.core.annotation.MqttClientSubscribe;
import org.springframework.stereotype.Service;
import java.nio.charset.StandardCharsets;
import java.util.Map;
/**
* 客户端消息监听
*
* @author L.cm
* @author ChangJin Wei(魏昌进)
*/
@Slf4j
@Service
public class MqttClientSubscribeListener {
@MqttClientSubscribe("/test/#")
public void subQos0(String topic, byte[] payload) {
log.info("topic:{} payload:{}", topic, new String(payload, StandardCharsets.UTF_8));
}
@MqttClientSubscribe(value = "/qos1/#", qos = MqttQoS.QOS1)
public void subQos1(String topic, byte[] payload) {
log.info("topic:{} payload:{}", topic, new String(payload, StandardCharsets.UTF_8));
}
@MqttClientSubscribe(
value = "/test/json",
deserialize = MqttJsonDeserializer.class // 2.4.5 开始支持 自定义序列化,默认 json 序列化
)
public void testJson(String topic, MqttPublishMessage message, Map<String, Object> data) {
// 2.4.5 开始支持,支持 2 到 3 个参数,字段类型映射规则(顺序)如下:
// String 字符串会默认映射到 topic
// Map<String, String> topicVars 会默认映射到 topic 中的变量解析v2.5.4支持),注意:别跟消息序列化的冲突,消息反序列化不要用 Map<String, String>
// MqttPublishMessage 会默认映射到 原始的消息,可以拿到 mqtt5 的 props 参数
// byte[] 会映射到 mqtt 消息内容 payload
// ByteBuffer 会映射到 mqtt 消息内容 payload
// 其他类型会走序列化,确保消息能够序列化,默认为 json 序列化
log.info("topic:{} json data:{}", topic, data);
}
@MqttClientSubscribe(value = "/test/object")
public void testJson(String topic, MqttPublishMessage message, User<User> data) {
log.info("topic:{} json data:{}", topic, data);
}
/**
* 订阅,参数为可选,但是参数数量必须大于 2
*
* @param topic topic 参数,可选参数
* @param topicVars 订阅 topic 模板 ${productKey} 中的变量解析v2.5.4支持),可选参数,注意:类型必须为 Map<String, String>
* @param payload 消息内容,以字节数组形式提供,可选参数,也可支持对象形式,默认 json 序列化
*/
@MqttClientSubscribe("/sys/${productKey}/${deviceName}/thing/sub/register")
public void thingSubRegister(String topic, Map<String, String> topicVars, byte[] payload) {
// 1.3.8 开始支持,@MqttClientSubscribe 注解支持 ${} 变量替换,会默认替换成 +
// 注意mica-mqtt 会先从 Spring boot 配置中替换参数 ${},如果存在配置会优先被替换。
log.info("topic:{} payload:{}", topic, new String(payload, StandardCharsets.UTF_8));
}
}

View File

@@ -0,0 +1,29 @@
package org.dromara.mica.mqtt.client.listener;
import lombok.extern.slf4j.Slf4j;
import org.dromara.mica.mqtt.codec.message.MqttPublishMessage;
import org.dromara.mica.mqtt.core.annotation.MqttClientSubscribe;
import org.springframework.stereotype.Service;
/**
* 客户端消息监听,注解在方法上
*
* @author L.cm
*/
@Slf4j
@Service
public class OtherMqttClientSubscribeListener {
@MqttClientSubscribe(
value = {
"$share/iothub/test/${a}",
"/test/${arg1}/${arg2}/${arg3}/${arg4}"
},
clientTemplateBean = "mqttClientTemplate1"
)
public void sub(String topic, MqttPublishMessage message, byte[] payload) {
log.info("topic:{} payload:{}", topic, new String(payload));
}
}

View File

@@ -0,0 +1,9 @@
package org.dromara.mica.mqtt.client.pojo;
import lombok.Data;
@Data
public class User<T> {
private String name;
private T girlfriend;
}

View File

@@ -0,0 +1,52 @@
package org.dromara.mica.mqtt.client.service;
import lombok.extern.slf4j.Slf4j;
import org.dromara.mica.mqtt.spring.client.MqttClientTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.nio.charset.StandardCharsets;
/**
* @author wsq
*/
@Slf4j
@Service
public class ClientService {
/**
* 使用 默认的 mqtt client
*/
@Autowired
@Qualifier(MqttClientTemplate.DEFAULT_CLIENT_TEMPLATE_BEAN)
private MqttClientTemplate client;
@Autowired
private HelloInterfaceA helloInterfaceA;
@Autowired
private HelloInterfaceB helloInterfaceB;
public boolean publish(String body) {
client.publish("/test/client", body.getBytes(StandardCharsets.UTF_8));
return true;
}
public boolean publishHelloInterfaceA(String body) {
helloInterfaceA.sayHello(body.getBytes(StandardCharsets.UTF_8));
return true;
}
public boolean publishHelloInterfaceB(String body) {
helloInterfaceB.sayHello(body.getBytes(StandardCharsets.UTF_8));
return true;
}
public boolean sub() {
client.subQos0("/test/#", (context, topic, message, payload) -> {
log.info("{}\t{}", topic, new String(payload, StandardCharsets.UTF_8));
});
return true;
}
}

View File

@@ -0,0 +1,31 @@
/*
* Copyright (c) 2019-2029, Dreamlu 卢春梦 (596392912@qq.com & dreamlu.net).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dromara.mica.mqtt.client.service;
import org.dromara.mica.mqtt.core.annotation.MqttClientPublish;
import org.dromara.mica.mqtt.core.annotation.MqttPayload;
import org.dromara.mica.mqtt.spring.client.annotation.MqttClient;
/**
* @author ChangJin Wei (魏昌进)
*/
@MqttClient
public interface HelloInterfaceA {
@MqttClientPublish("/test/HelloInterfaceA")
void sayHello(@MqttPayload Object payload);
}

View File

@@ -0,0 +1,32 @@
/*
* Copyright (c) 2019-2029, Dreamlu 卢春梦 (596392912@qq.com & dreamlu.net).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dromara.mica.mqtt.client.service;
import org.dromara.mica.mqtt.core.annotation.MqttClientPublish;
import org.dromara.mica.mqtt.core.annotation.MqttPayload;
import org.dromara.mica.mqtt.spring.client.annotation.MqttClient;
/**
* @author ChangJin Wei (魏昌进)
*/
@MqttClient
public interface HelloInterfaceB {
@MqttClientPublish("/test/HelloInterfaceB")
void sayHello(@MqttPayload Object payload);
}

View File

@@ -0,0 +1,46 @@
server:
port: 30012
spring:
application:
name: mica-mqtt-client
# mqtt-client 配置
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 改成了 username
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
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
will-message:
topic: /test/offline
message: down
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 密码
topic1: /test2/#
springdoc:
swagger-ui:
urls:
- name: swagger
url: /v3/api-docs
logging:
level:
root: info
server: info # t-io 服务端默认日志
org.tio: info # t-io 服务端默认日志
org.dromara.mica.mqtt: info # mica-mqtt 日志

View File

@@ -0,0 +1,12 @@
${AnsiColor.BRIGHT_BLUE}## ## #### ###### ### ${AnsiColor.RED} ## ## ####### ######## ########
${AnsiColor.BRIGHT_BLUE}### ### ## ## ## ## ## ${AnsiColor.RED} ### ### ## ## ## ##
${AnsiColor.BRIGHT_BLUE}#### #### ## ## ## ## ${AnsiColor.RED} #### #### ## ## ## ##
${AnsiColor.BRIGHT_BLUE}## ### ## ## ## ## ##${AnsiColor.RED} ## ### ## ## ## ## ##
${AnsiColor.BRIGHT_BLUE}## ## ## ## #########${AnsiColor.RED} ## ## ## ## ## ## ##
${AnsiColor.BRIGHT_BLUE}## ## ## ## ## ## ##${AnsiColor.RED} ## ## ## ## ## ##
${AnsiColor.BRIGHT_BLUE}## ## #### ###### ## ##${AnsiColor.RED} ## ## ##### ## ## ##
https://www.dreamlu.net
${AnsiColor.BRIGHT_BLUE}:: ${spring.application.name} :: Running Spring Boot ${spring-boot.version} 🏃🏃🏃 ${AnsiColor.DEFAULT}