first commit
This commit is contained in:
269
starter/mica-mqtt-client-spring-boot-starter/README.md
Normal file
269
starter/mica-mqtt-client-spring-boot-starter/README.md
Normal file
@@ -0,0 +1,269 @@
|
||||
# mica-mqtt-client-spring-boot-starter 使用文档
|
||||
|
||||
## 版本兼容
|
||||
| 要求 | Spring boot 版本 |
|
||||
|-----|----------------|
|
||||
| 最高 | 4.x |
|
||||
| 最低 | 2.1.0.RELEASE |
|
||||
|
||||
## 一、添加依赖
|
||||
|
||||
```xml
|
||||
<dependency>
|
||||
<groupId>org.dromara.mica-mqtt</groupId>
|
||||
<artifactId>mica-mqtt-client-spring-boot-starter</artifactId>
|
||||
<version>${最新版本}</version>
|
||||
</dependency>
|
||||
```
|
||||
|
||||
## 二、mqtt 客户端
|
||||
|
||||
### 2.1 配置项示例
|
||||
```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
|
||||
client-id: 000001 # 客户端Id(非常重要,一般为设备 sn,不可重复)
|
||||
username: mica # 认证的用户名,注意:2.5.x 开始将 user-name 改成了 username
|
||||
password: 123456 # 认证的密码
|
||||
global-subscribe: # 全局订阅的 topic,可被全局监听到,保留 session 停机重启,依然可以接受到消息。(2.2.9开始支持)
|
||||
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
|
||||
session-expiry-interval-secs: 0 # 开启保留 session 时,session 的有效期,默认:0(2.4.2 开始支持)
|
||||
biz-thread-pool-size: 2 # mqtt 工作线程数,默认:2,如果消息量比较大,处理较慢,例如做 emqx 的转发消息处理,可以调大此参数(2.4.2 开始支持)
|
||||
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 密码
|
||||
```
|
||||
|
||||
注意:**ssl** 存在三种情况
|
||||
|
||||
| 服务端开启ssl | 客户端 |
|
||||
| ---------------------------------------- | --------------------------------------------- |
|
||||
| ClientAuth 为 NONE(不需要客户端验证) | 仅仅需要开启 ssl 即可不用配置证书 |
|
||||
| ClientAuth 为 OPTIONAL(与客户端协商) | 需开启 ssl 并且配置 truststore 证书 |
|
||||
| ClientAuth 为 REQUIRE (必须的客户端验证) | 需开启 ssl 并且配置 truststore、 keystore证书 |
|
||||
|
||||
|
||||
### 2.2 可实现接口(注册成 Spring Bean 即可)
|
||||
|
||||
| 接口 | 是否必须 | 说明 |
|
||||
| --------------------------- |------|--------------------------------|
|
||||
| IMqttClientConnectListener | 否 | 客户端连接成功监听 |
|
||||
| IMqttClientGlobalMessageListener | 否 | 全局消息监听,可以监听到所有订阅消息。(2.2.9开始支持) |
|
||||
|
||||
### 2.3 客户端上下线监听
|
||||
使用 Spring event 解耦客户端上下线监听,注意: `1.3.4` 开始支持。会跟自定义的 `IMqttClientConnectListener` 实现冲突,取一即可。
|
||||
|
||||
```java
|
||||
/**
|
||||
* 示例:客户端连接状态监听
|
||||
*
|
||||
* @author L.cm
|
||||
*/
|
||||
@Service
|
||||
public class MqttClientConnectListener {
|
||||
private static final Logger logger = LoggerFactory.getLogger(MqttClientConnectListener.class);
|
||||
|
||||
@Autowired
|
||||
private MqttClientCreator mqttClientCreator;
|
||||
|
||||
@EventListener
|
||||
public void onConnected(MqttConnectedEvent event) {
|
||||
logger.info("MqttConnectedEvent:{}", event);
|
||||
}
|
||||
|
||||
@EventListener
|
||||
public void onDisconnect(MqttDisconnectEvent event) {
|
||||
// 离线时更新重连时的密码,适用于类似阿里云 mqtt clientId 连接带时间戳的方式
|
||||
logger.info("MqttDisconnectEvent:{}", event);
|
||||
// 在断线时更新 clientId、username、password
|
||||
mqttClientCreator.clientId("newClient" + System.currentTimeMillis())
|
||||
.username("newUserName")
|
||||
.password("newPassword");
|
||||
}
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
### 2.4 自定义 java 配置(可选)
|
||||
|
||||
```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-----------------");
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
### 2.5 订阅示例
|
||||
```java
|
||||
@Service
|
||||
public class MqttClientSubscribeListener {
|
||||
private static final Logger logger = LoggerFactory.getLogger(MqttClientSubscribeListener.class);
|
||||
|
||||
@MqttClientSubscribe("/test/#")
|
||||
public void subQos0(String topic, byte[] payload) {
|
||||
logger.info("topic:{} payload:{}", topic, new String(payload, StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@MqttClientSubscribe(value = "/qos1/#", qos = MqttQoS.QOS1)
|
||||
public void subQos1(String topic, byte[] payload) {
|
||||
logger.info("topic:{} payload:{}", topic, new String(payload, StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@MqttClientSubscribe("/sys/${productKey}/${deviceName}/thing/sub/register")
|
||||
public void thingSubRegister(String topic, byte[] payload) {
|
||||
// 1.3.8 开始支持,@MqttClientSubscribe 注解支持 ${} 变量替换,会默认替换成 +
|
||||
// 注意:mica-mqtt 会先从 Spring boot 配置中替换参数 ${},如果存在配置会优先被替换。
|
||||
logger.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, TestJsonBean data) {
|
||||
// 2.4.5 开始支持,支持 2 到 3 个参数,字段类型映射规则如下
|
||||
// String 字符串会默认映射到 topic,
|
||||
// MqttPublishMessage 会默认映射到 原始的消息,可以拿到 mqtt5 的 props 参数
|
||||
// byte[] 会映射到 mqtt 消息内容 payload
|
||||
// ByteBuffer 会映射到 mqtt 消息内容 payload
|
||||
// 其他类型会走序列化,确保消息能够序列化,默认为 json 序列化
|
||||
logger.info("topic:{} json data:{}", topic, data);
|
||||
}
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
### 2.6 共享订阅 topic 说明
|
||||
mica-mqtt 支持两种**共享订阅**方式:
|
||||
|
||||
1. 共享订阅:订阅前缀 `$queue/`,多个客户端订阅了 `$queue/topic`,发布者发布到 `topic`,则只有一个客户端会接收到消息。
|
||||
2. 分组订阅:订阅前缀 `$share/<group>/`,组客户端订阅了 `$share/group1/topic`、`$share/group2/topic`..,发布者发布到 `topic`,则消息会发布到每个 **group** 中,但是每个 **group** 中只有一个客户端会接收到消息。
|
||||
|
||||
**注意:** 如果发布的 `topic` 以 `/` 开头,例如:`/topic/test`,需要订阅 `$share/group1//topic/test`,另外 mica-mqtt 默认随机消息路由,共享订阅的多个客户端会随机收到消息。
|
||||
|
||||
### 2.7 MqttClientTemplate 使用示例
|
||||
|
||||
```java
|
||||
|
||||
import org.dromara.mica.mqtt.spring.client.MqttClientTemplate;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/**
|
||||
* @author wsq
|
||||
*/
|
||||
@Service
|
||||
public class MainService {
|
||||
private static final Logger logger = LoggerFactory.getLogger(MainService.class);
|
||||
@Autowired
|
||||
private MqttClientTemplate client;
|
||||
|
||||
public boolean publish() {
|
||||
client.publish("/test/client", "mica最牛皮".getBytes(StandardCharsets.UTF_8));
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean sub() {
|
||||
client.subQos0("/test/#", (context, topic, message, payload) -> {
|
||||
logger.info(topic + '\t' + new String(payload, StandardCharsets.UTF_8));
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
## 3. 多个 mqtt client 客户端
|
||||
### 3.1 自定义 MqttClientTemplate bean 2.2.11 开始已简化,老版本建议先升级。
|
||||
```java
|
||||
@Configuration
|
||||
public class OtherMqttClientConfiguration {
|
||||
|
||||
@Bean("mqttClientTemplate1")
|
||||
public MqttClientTemplate mqttClientTemplate1() {
|
||||
MqttClientCreator mqttClientCreator1 = MqttClient.create()
|
||||
.ip("mqtt.dreamlu.net")
|
||||
.username("mica")
|
||||
.password("mica");
|
||||
return new MqttClientTemplate(mqttClientCreator1);
|
||||
}
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
### 3.2 修改 starter 自带的 MqttClientTemplate Bean 引入
|
||||
由于现在加入了一个新的名为 `mqttClientTemplate1` MqttClientTemplate,老的 starter 内置的 MqttClientTemplate 引入也需要添加 bean name。
|
||||
|
||||
```java
|
||||
@Autowired
|
||||
@Qualifier(MqttClientTemplate.DEFAULT_CLIENT_TEMPLATE_BEAN)
|
||||
private MqttClientTemplate mqttClientTemplate;
|
||||
```
|
||||
|
||||
### 3.3 新加入的 mqttClientTemplate1 MqttClientTemplate bean 引入
|
||||
```java
|
||||
@Autowired
|
||||
@Qualifier("mqttClientTemplate1")
|
||||
private MqttClientTemplate mqttClientTemplate;
|
||||
```
|
||||
|
||||
### 3.4 新加入的 mqttClientTemplate1 注解订阅
|
||||
注意:由于 `@MqttClientSubscribe` clientTemplateBean 默认是 `MqttClientTemplate.DEFAULT_CLIENT_TEMPLATE_BEAN`,所以新增的 `mqttClientTemplate1` 注解订阅的时候也需要配置。
|
||||
```java
|
||||
@MqttClientSubscribe(
|
||||
value = "/#",
|
||||
clientTemplateBean = "mqttClientTemplate1"
|
||||
)
|
||||
public void sub1(String topic, byte[] payload) {
|
||||
logger.info("topic:{} payload:{}", topic, ByteBufferUtil.toString(payload));
|
||||
}
|
||||
```
|
||||
|
||||
### 接口代理
|
||||
|
||||
```java
|
||||
|
||||
@EnableMqttClients
|
||||
public class MqttClientApplication {
|
||||
// ...
|
||||
}
|
||||
|
||||
@MqttClient(clientBean = "mqttClientTemplate")
|
||||
public interface HelloInterfaceB {
|
||||
|
||||
@MqttClientPublish("/test/HelloInterfaceB")
|
||||
void sayHello(@MqttPayload Object payload);
|
||||
|
||||
}
|
||||
```
|
||||
38
starter/mica-mqtt-client-spring-boot-starter/pom.xml
Normal file
38
starter/mica-mqtt-client-spring-boot-starter/pom.xml
Normal file
@@ -0,0 +1,38 @@
|
||||
<?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>
|
||||
<parent>
|
||||
<groupId>org.dromara.mica-mqtt</groupId>
|
||||
<artifactId>starter</artifactId>
|
||||
<version>${revision}</version>
|
||||
</parent>
|
||||
<artifactId>mica-mqtt-client-spring-boot-starter</artifactId>
|
||||
<name>${project.artifactId}</name>
|
||||
<url>https://mica-mqtt.dreamlu.net/guide/spring/client.html</url>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.dromara.mica-mqtt</groupId>
|
||||
<artifactId>mica-mqtt-client</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-autoconfigure</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<!-- mica-auto 自动生成 spring.factories、spring-devtools.properties 配置 -->
|
||||
<dependency>
|
||||
<groupId>net.dreamlu</groupId>
|
||||
<artifactId>mica-auto</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,56 @@
|
||||
/*
|
||||
* 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.spring.client;
|
||||
|
||||
|
||||
import org.springframework.beans.factory.FactoryBean;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
|
||||
/**
|
||||
* @author ChangJin Wei (魏昌进)
|
||||
*/
|
||||
public class MqttClientFactoryBean<T> implements FactoryBean<T>, ApplicationContextAware {
|
||||
|
||||
private final Class<T> interfaceClass;
|
||||
|
||||
private final String mqttClientTemplateBeanName;
|
||||
|
||||
private ApplicationContext applicationContext;
|
||||
|
||||
public MqttClientFactoryBean(Class<T> interfaceClass, String mqttClientTemplateBeanName) {
|
||||
this.interfaceClass = interfaceClass;
|
||||
this.mqttClientTemplateBeanName = mqttClientTemplateBeanName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T getObject() {
|
||||
MqttClientTemplate mqttClientTemplate =
|
||||
applicationContext.getBean(mqttClientTemplateBeanName, MqttClientTemplate.class);
|
||||
return mqttClientTemplate.getInterface(interfaceClass);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<?> getObjectType() {
|
||||
return interfaceClass;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setApplicationContext(ApplicationContext applicationContext) {
|
||||
this.applicationContext = applicationContext;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
/*
|
||||
* 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.spring.client;
|
||||
|
||||
import org.dromara.mica.mqtt.spring.client.annotation.EnableMqttClients;
|
||||
import org.dromara.mica.mqtt.spring.client.annotation.MqttClient;
|
||||
import org.dromara.mica.mqtt.spring.client.config.MqttClientConfiguration;
|
||||
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
|
||||
import org.springframework.beans.factory.config.BeanDefinition;
|
||||
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
|
||||
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
|
||||
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
|
||||
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
|
||||
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
|
||||
import org.springframework.core.annotation.AnnotationUtils;
|
||||
import org.springframework.core.type.AnnotationMetadata;
|
||||
import org.springframework.core.type.filter.AnnotationTypeFilter;
|
||||
import org.springframework.util.ClassUtils;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* @author ChangJin Wei (魏昌进)
|
||||
*/
|
||||
@AutoConfigureAfter(MqttClientConfiguration.class)
|
||||
public class MqttClientRegistrar implements ImportBeanDefinitionRegistrar {
|
||||
|
||||
@Override
|
||||
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
|
||||
Map<String, Object> attrs = importingClassMetadata.getAnnotationAttributes(EnableMqttClients.class.getName());
|
||||
String[] basePackages = (String[]) attrs.get("basePackages");
|
||||
|
||||
if (basePackages == null || basePackages.length == 0) {
|
||||
basePackages = new String[]{ClassUtils.getPackageName(importingClassMetadata.getClassName())};
|
||||
}
|
||||
|
||||
for (String basePackage : basePackages) {
|
||||
scanAndRegisterClients(basePackage, registry);
|
||||
}
|
||||
}
|
||||
|
||||
private void scanAndRegisterClients(String basePackage, BeanDefinitionRegistry registry) {
|
||||
ClassPathScanningCandidateComponentProvider scanner = getScanner();
|
||||
scanner.addIncludeFilter(new AnnotationTypeFilter(MqttClient.class));
|
||||
|
||||
Set<BeanDefinition> candidates = scanner.findCandidateComponents(basePackage);
|
||||
for (BeanDefinition candidate : candidates) {
|
||||
try {
|
||||
String className = candidate.getBeanClassName();
|
||||
Class<?> interfaceClass = Class.forName(className);
|
||||
|
||||
MqttClient mqttClientAnnotation = AnnotationUtils.findAnnotation(interfaceClass, MqttClient.class);
|
||||
if (mqttClientAnnotation == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
String mqttClientTemplateBeanName = mqttClientAnnotation.clientBean();
|
||||
|
||||
// 构造 FactoryBean,注入接口和客户端 Bean 名称
|
||||
BeanDefinitionBuilder builder = BeanDefinitionBuilder
|
||||
.genericBeanDefinition(MqttClientFactoryBean.class);
|
||||
builder.addConstructorArgValue(interfaceClass);
|
||||
builder.addConstructorArgValue(mqttClientTemplateBeanName);
|
||||
|
||||
// 注册为 Spring Bean,使用接口类名作为 beanName
|
||||
String beanName = ClassUtils.getShortNameAsProperty(interfaceClass);
|
||||
registry.registerBeanDefinition(beanName, builder.getBeanDefinition());
|
||||
|
||||
} catch (ClassNotFoundException e) {
|
||||
throw new RuntimeException("Failed to load MQTT client interface", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private ClassPathScanningCandidateComponentProvider getScanner() {
|
||||
return new ClassPathScanningCandidateComponentProvider(false) {
|
||||
@Override
|
||||
protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
|
||||
return true; // 允许接口作为候选组件
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
/*
|
||||
* 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.spring.client;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.dromara.mica.mqtt.core.annotation.MqttClientSubscribe;
|
||||
import org.dromara.mica.mqtt.core.client.IMqttClientMessageListener;
|
||||
import org.dromara.mica.mqtt.core.client.IMqttClientSession;
|
||||
import org.dromara.mica.mqtt.core.deserialize.MqttDeserializer;
|
||||
import org.dromara.mica.mqtt.core.util.TopicUtil;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.factory.config.BeanPostProcessor;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.core.annotation.AnnotationUtils;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.util.ClassUtils;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* MqttClient 订阅监听器
|
||||
*
|
||||
* @author L.cm
|
||||
* @author ChangJin Wei(魏昌进)
|
||||
*/
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class MqttClientSubscribeDetector implements BeanPostProcessor {
|
||||
private final ApplicationContext applicationContext;
|
||||
|
||||
@Override
|
||||
public Object postProcessAfterInitialization(@NonNull Object bean, String beanName) throws BeansException {
|
||||
Class<?> userClass = ClassUtils.getUserClass(bean);
|
||||
if (bean instanceof IMqttClientMessageListener) {
|
||||
// 1. 查找类上的 MqttClientSubscribe 注解
|
||||
processClassLevelSubscription(userClass, bean);
|
||||
} else {
|
||||
// 2. 查找方法上的 MqttClientSubscribe 注解
|
||||
processMethodLevelSubscriptions(userClass, bean);
|
||||
}
|
||||
return bean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理类上的 @MqttClientSubscribe 注解。
|
||||
* 为实现了 IMqttClientMessageListener 接口的类自动注册 MQTT 订阅。
|
||||
*/
|
||||
protected void processClassLevelSubscription(Class<?> userClass, Object bean) {
|
||||
MqttClientSubscribe subscribe = AnnotationUtils.findAnnotation(userClass, MqttClientSubscribe.class);
|
||||
if (subscribe != null) {
|
||||
IMqttClientSession clientSession = getMqttClientSession(subscribe.clientTemplateBean());
|
||||
String[] topicFilters = getTopicFilters(subscribe.value());
|
||||
clientSession.addSubscriptionList(topicFilters, subscribe.qos(), (IMqttClientMessageListener) bean);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理方法上的 @MqttClientSubscribe 注解。
|
||||
* 为符合签名的方法自动注册 MQTT 订阅监听器。
|
||||
*/
|
||||
protected void processMethodLevelSubscriptions(Class<?> userClass, Object bean) {
|
||||
ReflectionUtils.doWithMethods(userClass, method -> {
|
||||
MqttClientSubscribe subscribe = AnnotationUtils.findAnnotation(method, MqttClientSubscribe.class);
|
||||
if (subscribe != null) {
|
||||
// 1. 校验必须为 public 和非 static 的方法
|
||||
int modifiers = method.getModifiers();
|
||||
if (Modifier.isStatic(modifiers)) {
|
||||
throw new IllegalArgumentException("@MqttClientSubscribe on method " + method + " must not static.");
|
||||
}
|
||||
if (!Modifier.isPublic(modifiers)) {
|
||||
throw new IllegalArgumentException("@MqttClientSubscribe on method " + method + " must public.");
|
||||
}
|
||||
// 2. 校验 method 入参数支持 2 ~ 3 个
|
||||
int paramCount = method.getParameterCount();
|
||||
if (paramCount < 2 || paramCount > 3) {
|
||||
throw new IllegalArgumentException("@MqttClientSubscribe on method " + method + " parameter count must 2 ~ 3.");
|
||||
}
|
||||
// 3. 订阅存储,保存后,连接成功后会自动订阅
|
||||
IMqttClientSession clientSession = getMqttClientSession(subscribe.clientTemplateBean());
|
||||
// 4. 订阅的 topic 转换
|
||||
String[] topicTemplates = subscribe.value();
|
||||
String[] topicFilters = getTopicFilters(topicTemplates);
|
||||
// 5. 自定义的反序列化,支持 Spring bean 或者 无参构造器初始化
|
||||
Class<? extends MqttDeserializer> deserialized = subscribe.deserialize();
|
||||
@SuppressWarnings("unchecked")
|
||||
MqttDeserializer deserializer = getMqttDeserializer((Class<MqttDeserializer>) deserialized);
|
||||
// 6. 构造监听器
|
||||
MqttClientSubscribeListener listener = new MqttClientSubscribeListener(bean, method, topicTemplates, topicFilters, deserializer);
|
||||
// 7. mqtt 订阅
|
||||
clientSession.addSubscriptionList(topicFilters, subscribe.qos(), listener);
|
||||
}
|
||||
}, ReflectionUtils.USER_DECLARED_METHODS);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取 IMqttClientSession
|
||||
*
|
||||
* @param beanName beanName
|
||||
* @return IMqttClientSession
|
||||
*/
|
||||
protected IMqttClientSession getMqttClientSession(String beanName) {
|
||||
// 添加对占位符的支持:gitee #ID7PF6 https://gitee.com/dromara/mica-mqtt/issues/ID7PF6
|
||||
String resolvedBeanName = applicationContext.getEnvironment().resolvePlaceholders(beanName);
|
||||
return applicationContext.getBean(resolvedBeanName, MqttClientTemplate.class).getClientCreator().getClientSession();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取解码器
|
||||
*
|
||||
* @param deserializerType deserializerType
|
||||
* @return 解码器
|
||||
*/
|
||||
protected MqttDeserializer getMqttDeserializer(Class<MqttDeserializer> deserializerType) {
|
||||
return applicationContext.getBeanProvider(deserializerType)
|
||||
.getIfAvailable(() -> BeanUtils.instantiateClass(deserializerType));
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换 topic filter
|
||||
*
|
||||
* @param topicTemplates 订阅含有变量的 topicTemplate
|
||||
* @return topic filter
|
||||
*/
|
||||
protected String[] getTopicFilters(String[] topicTemplates) {
|
||||
// 1. 替换 Spring boot env 变量
|
||||
// 2. 替换订阅中的其他变量
|
||||
Environment environment = applicationContext.getEnvironment();
|
||||
return Arrays.stream(topicTemplates)
|
||||
.map(environment::resolvePlaceholders)
|
||||
.map(TopicUtil::getTopicFilter)
|
||||
.toArray(String[]::new);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/*
|
||||
* 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.spring.client;
|
||||
|
||||
import org.dromara.mica.mqtt.core.annotation.MqttClientSubscribe;
|
||||
import org.springframework.beans.factory.config.BeanDefinition;
|
||||
import org.springframework.boot.LazyInitializationExcludeFilter;
|
||||
import org.springframework.core.annotation.AnnotationUtils;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* mqtt 客户端订阅延迟加载排除
|
||||
*
|
||||
* @author L.cm
|
||||
*/
|
||||
public class MqttClientSubscribeLazyFilter implements LazyInitializationExcludeFilter {
|
||||
|
||||
@Override
|
||||
public boolean isExcluded(String beanName, BeanDefinition beanDefinition, Class<?> beanType) {
|
||||
// 类上有注解的情况
|
||||
MqttClientSubscribe subscribe = AnnotationUtils.findAnnotation(beanType, MqttClientSubscribe.class);
|
||||
if (subscribe != null) {
|
||||
return true;
|
||||
}
|
||||
// 方法上的注解
|
||||
List<Method> methodList = new ArrayList<>();
|
||||
ReflectionUtils.doWithMethods(beanType, method -> {
|
||||
MqttClientSubscribe clientSubscribe = AnnotationUtils.findAnnotation(method, MqttClientSubscribe.class);
|
||||
if (clientSubscribe != null) {
|
||||
methodList.add(method);
|
||||
}
|
||||
}, ReflectionUtils.USER_DECLARED_METHODS);
|
||||
return !methodList.isEmpty();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
/*
|
||||
* 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.spring.client;
|
||||
|
||||
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.deserialize.MqttDeserializer;
|
||||
import org.dromara.mica.mqtt.core.function.ParamValueFunction;
|
||||
import org.dromara.mica.mqtt.core.util.MethodParamUtil;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
import org.tio.core.ChannelContext;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
/**
|
||||
* MqttClientSubscribe 注解订阅监听
|
||||
*
|
||||
* @author L.cm
|
||||
*/
|
||||
@Slf4j
|
||||
public class MqttClientSubscribeListener implements IMqttClientMessageListener {
|
||||
private final Object bean;
|
||||
private final Method method;
|
||||
private final ParamValueFunction[] paramValueFunctions;
|
||||
|
||||
public MqttClientSubscribeListener(Object bean, Method method, String[] topicTemplates, String[] topicFilters, MqttDeserializer deserializer) {
|
||||
this.bean = bean;
|
||||
this.method = method;
|
||||
this.paramValueFunctions = MethodParamUtil.getParamValueFunctions(method, topicTemplates, topicFilters, deserializer);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMessage(ChannelContext context, String topic, MqttPublishMessage message, byte[] payload) {
|
||||
// 获取方法参数
|
||||
Object[] args = getMethodParameters(context, topic, message, payload);
|
||||
// 反射执行方法
|
||||
ReflectionUtils.invokeMethod(method, bean, args);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取反射参数
|
||||
*
|
||||
* @param context context
|
||||
* @param topic topic
|
||||
* @param message message
|
||||
* @param payload payload
|
||||
* @return Object array
|
||||
*/
|
||||
protected Object[] getMethodParameters(ChannelContext context, String topic, MqttPublishMessage message, byte[] payload) {
|
||||
int length = paramValueFunctions.length;
|
||||
Object[] parameters = new Object[length];
|
||||
for (int i = 0; i < length; i++) {
|
||||
ParamValueFunction function = paramValueFunctions[i];
|
||||
parameters[i] = function.getValue(context, topic, message, payload);
|
||||
}
|
||||
return parameters;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,449 @@
|
||||
/*
|
||||
* 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.spring.client;
|
||||
|
||||
import lombok.Getter;
|
||||
import org.dromara.mica.mqtt.codec.message.builder.MqttPublishBuilder;
|
||||
import org.dromara.mica.mqtt.codec.properties.MqttProperties;
|
||||
import org.dromara.mica.mqtt.codec.MqttQoS;
|
||||
import org.dromara.mica.mqtt.core.client.*;
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.factory.DisposableBean;
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
import org.springframework.beans.factory.SmartInitializingSingleton;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.tio.client.ClientChannelContext;
|
||||
import org.tio.client.TioClient;
|
||||
import org.tio.client.TioClientConfig;
|
||||
import org.tio.utils.timer.TimerTask;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* mqtt client 模板
|
||||
*
|
||||
* @author wsq(冷月宫主)
|
||||
* @author ChangJin Wei (魏昌进)
|
||||
*/
|
||||
public class MqttClientTemplate implements ApplicationContextAware, SmartInitializingSingleton, InitializingBean, DisposableBean, Ordered, IMqttClient {
|
||||
public static final String DEFAULT_CLIENT_TEMPLATE_BEAN = "mqttClientTemplate";
|
||||
@Getter
|
||||
private final MqttClientCreator clientCreator;
|
||||
private ApplicationContext applicationContext;
|
||||
private MqttClient client;
|
||||
|
||||
public MqttClientTemplate(MqttClientCreator clientCreator) {
|
||||
this.clientCreator = clientCreator;
|
||||
}
|
||||
|
||||
/**
|
||||
* 订阅
|
||||
*
|
||||
* @param topicFilter topicFilter
|
||||
* @param listener MqttMessageListener
|
||||
* @return MqttClient
|
||||
*/
|
||||
public MqttClient subQos0(String topicFilter, IMqttClientMessageListener listener) {
|
||||
return client.subscribe(topicFilter, MqttQoS.QOS0, listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* 订阅
|
||||
*
|
||||
* @param topicFilter topicFilter
|
||||
* @param listener MqttMessageListener
|
||||
* @return MqttClient
|
||||
*/
|
||||
public MqttClient subQos1(String topicFilter, IMqttClientMessageListener listener) {
|
||||
return client.subscribe(topicFilter, MqttQoS.QOS1, listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* 订阅
|
||||
*
|
||||
* @param topicFilter topicFilter
|
||||
* @param listener MqttMessageListener
|
||||
* @return MqttClient
|
||||
*/
|
||||
public MqttClient subQos2(String topicFilter, IMqttClientMessageListener listener) {
|
||||
return client.subscribe(topicFilter, MqttQoS.QOS2, listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* 订阅
|
||||
*
|
||||
* @param mqttQoS MqttQoS
|
||||
* @param topicFilter topicFilter
|
||||
* @param listener MqttMessageListener
|
||||
* @return MqttClient
|
||||
*/
|
||||
public MqttClient subscribe(MqttQoS mqttQoS, String topicFilter, IMqttClientMessageListener listener) {
|
||||
return client.subscribe(mqttQoS, topicFilter, listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* 订阅
|
||||
*
|
||||
* @param mqttQoS MqttQoS
|
||||
* @param topicFilter topicFilter
|
||||
* @param listener MqttMessageListener
|
||||
* @return MqttClient
|
||||
*/
|
||||
public MqttClient subscribe(String topicFilter, MqttQoS mqttQoS, IMqttClientMessageListener listener) {
|
||||
return client.subscribe(topicFilter, mqttQoS, listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* 订阅
|
||||
*
|
||||
* @param mqttQoS MqttQoS
|
||||
* @param topicFilter topicFilter
|
||||
* @param listener MqttMessageListener
|
||||
* @param properties MqttProperties
|
||||
* @return MqttClient
|
||||
*/
|
||||
public MqttClient subscribe(String topicFilter, MqttQoS mqttQoS, IMqttClientMessageListener listener, MqttProperties properties) {
|
||||
return client.subscribe(topicFilter, mqttQoS, listener, properties);
|
||||
}
|
||||
|
||||
/**
|
||||
* 订阅
|
||||
*
|
||||
* @param topicFilters topicFilter 数组
|
||||
* @param mqttQoS MqttQoS
|
||||
* @param listener MqttMessageListener
|
||||
* @return MqttClient
|
||||
*/
|
||||
public MqttClient subscribe(String[] topicFilters, MqttQoS mqttQoS, IMqttClientMessageListener listener) {
|
||||
return client.subscribe(topicFilters, mqttQoS, listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* 订阅
|
||||
*
|
||||
* @param topicFilters topicFilter 数组
|
||||
* @param mqttQoS MqttQoS
|
||||
* @param listener MqttMessageListener
|
||||
* @param properties MqttProperties
|
||||
* @return MqttClient
|
||||
*/
|
||||
public MqttClient subscribe(String[] topicFilters, MqttQoS mqttQoS, IMqttClientMessageListener listener, MqttProperties properties) {
|
||||
return client.subscribe(topicFilters, mqttQoS, listener, properties);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量订阅
|
||||
*
|
||||
* @param subscriptionList 订阅集合
|
||||
* @return MqttClient
|
||||
*/
|
||||
public MqttClient subscribe(List<MqttClientSubscription> subscriptionList) {
|
||||
return client.subscribe(subscriptionList);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量订阅
|
||||
*
|
||||
* @param subscriptionList 订阅集合
|
||||
* @param properties MqttProperties
|
||||
* @return MqttClient
|
||||
*/
|
||||
public MqttClient subscribe(List<MqttClientSubscription> subscriptionList, MqttProperties properties) {
|
||||
return client.subscribe(subscriptionList, properties);
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消订阅
|
||||
*
|
||||
* @param topicFilters topicFilter 集合
|
||||
* @return MqttClient
|
||||
*/
|
||||
public MqttClient unSubscribe(String... topicFilters) {
|
||||
return client.unSubscribe(topicFilters);
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消订阅
|
||||
*
|
||||
* @param topicFilters topicFilter 集合
|
||||
* @return MqttClient
|
||||
*/
|
||||
public MqttClient unSubscribe(List<String> topicFilters) {
|
||||
return client.unSubscribe(topicFilters);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发布消息
|
||||
*
|
||||
* @param topic topic
|
||||
* @param payload 消息内容
|
||||
* @return 是否发送成功
|
||||
*/
|
||||
public boolean publish(String topic, Object payload) {
|
||||
return client.publish(topic, payload, MqttQoS.QOS0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发布消息
|
||||
*
|
||||
* @param topic topic
|
||||
* @param payload 消息内容
|
||||
* @param qos MqttQoS
|
||||
* @return 是否发送成功
|
||||
*/
|
||||
public boolean publish(String topic, Object payload, MqttQoS qos) {
|
||||
return client.publish(topic, payload, qos);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发布消息
|
||||
*
|
||||
* @param topic topic
|
||||
* @param payload 消息内容
|
||||
* @param retain 是否在服务器上保留消息
|
||||
* @return 是否发送成功
|
||||
*/
|
||||
public boolean publish(String topic, Object payload, boolean retain) {
|
||||
return client.publish(topic, payload, retain);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发布消息
|
||||
*
|
||||
* @param topic topic
|
||||
* @param payload 消息体
|
||||
* @param qos MqttQoS
|
||||
* @param retain 是否在服务器上保留消息
|
||||
* @return 是否发送成功
|
||||
*/
|
||||
public boolean publish(String topic, Object payload, MqttQoS qos, boolean retain) {
|
||||
return client.publish(topic, payload, qos, retain);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发布消息
|
||||
*
|
||||
* @param topic topic
|
||||
* @param payload 消息体
|
||||
* @param qos MqttQoS
|
||||
* @param retain 是否在服务器上保留消息
|
||||
* @param properties MqttProperties
|
||||
* @return 是否发送成功
|
||||
*/
|
||||
public boolean publish(String topic, Object payload, MqttQoS qos, boolean retain, MqttProperties properties) {
|
||||
return client.publish(topic, payload, qos, retain, properties);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发布消息
|
||||
*
|
||||
* @param topic topic
|
||||
* @param payload 消息体
|
||||
* @param qos MqttQoS
|
||||
* @param builder PublishBuilder
|
||||
* @return 是否发送成功
|
||||
*/
|
||||
public boolean publish(String topic, Object payload, MqttQoS qos, Consumer<MqttPublishBuilder> builder) {
|
||||
return client.publish(topic, payload, qos, builder);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发布消息
|
||||
*
|
||||
* @param builder PublishBuilder
|
||||
* @return 是否发送成功
|
||||
*/
|
||||
public boolean publish(MqttPublishBuilder builder) {
|
||||
return client.publish(builder);
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加定时任务,注意:如果抛出异常,会终止后续任务,请自行处理异常
|
||||
*
|
||||
* @param command runnable
|
||||
* @param delay delay
|
||||
* @return TimerTask
|
||||
*/
|
||||
public TimerTask schedule(Runnable command, long delay) {
|
||||
return client.schedule(command, delay);
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加定时任务,注意:如果抛出异常,会终止后续任务,请自行处理异常
|
||||
*
|
||||
* @param command runnable
|
||||
* @param delay delay
|
||||
* @param executor 用于自定义线程池,处理耗时业务
|
||||
* @return TimerTask
|
||||
*/
|
||||
public TimerTask schedule(Runnable command, long delay, Executor executor) {
|
||||
return client.schedule(command, delay, executor);
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加定时任务
|
||||
*
|
||||
* @param command runnable
|
||||
* @param delay delay
|
||||
* @return TimerTask
|
||||
*/
|
||||
public TimerTask scheduleOnce(Runnable command, long delay) {
|
||||
return client.scheduleOnce(command, delay);
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加定时任务
|
||||
*
|
||||
* @param command runnable
|
||||
* @param delay delay
|
||||
* @param executor 用于自定义线程池,处理耗时业务
|
||||
* @return TimerTask
|
||||
*/
|
||||
public TimerTask scheduleOnce(Runnable command, long delay, Executor executor) {
|
||||
return client.scheduleOnce(command, delay, executor);
|
||||
}
|
||||
|
||||
/**
|
||||
* 重连
|
||||
*/
|
||||
public void reconnect() {
|
||||
client.reconnect();
|
||||
}
|
||||
|
||||
/**
|
||||
* 重连到新的服务端节点
|
||||
*
|
||||
* @param ip ip
|
||||
* @param port port
|
||||
* @return 是否成功
|
||||
*/
|
||||
public boolean reconnect(String ip, int port) {
|
||||
return client.reconnect(ip, port);
|
||||
}
|
||||
|
||||
/**
|
||||
* 断开 mqtt 连接
|
||||
*
|
||||
* @return 是否成功
|
||||
*/
|
||||
public boolean disconnect() {
|
||||
return client.disconnect();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 TioClient
|
||||
*
|
||||
* @return TioClient
|
||||
*/
|
||||
public TioClient getTioClient() {
|
||||
return client.getTioClient();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 ClientTioConfig
|
||||
*
|
||||
* @return ClientTioConfig
|
||||
*/
|
||||
public TioClientConfig getClientTioConfig() {
|
||||
return client.getClientTioConfig();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 ClientChannelContext
|
||||
*
|
||||
* @return ClientChannelContext
|
||||
*/
|
||||
public ClientChannelContext getContext() {
|
||||
return client.getContext();
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断客户端跟服务端是否连接
|
||||
*
|
||||
* @return 是否已经连接成功
|
||||
*/
|
||||
public boolean isConnected() {
|
||||
return client.isConnected();
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断客户端跟服务端是否断开连接
|
||||
*
|
||||
* @return 是否断连
|
||||
*/
|
||||
public boolean isDisconnected() {
|
||||
return client.isDisconnected();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 MqttClient
|
||||
*
|
||||
* @return MqttClient
|
||||
*/
|
||||
@Override
|
||||
public MqttClient getMqttClient() {
|
||||
return client;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
|
||||
this.applicationContext = applicationContext;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterPropertiesSet() throws Exception {
|
||||
// 需要支持注解订阅所以 clientSession 配置的时机要早一些
|
||||
IMqttClientSession clientSession = this.clientCreator.getClientSession();
|
||||
if (clientSession == null) {
|
||||
clientSession = this.applicationContext.getBeanProvider(IMqttClientSession.class)
|
||||
.getIfAvailable(DefaultMqttClientSession::new);
|
||||
this.clientCreator.clientSession(clientSession);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterSingletonsInstantiated() {
|
||||
// 配置客户端连接监听器
|
||||
this.applicationContext.getBeanProvider(IMqttClientConnectListener.class).ifAvailable(clientCreator::connectListener);
|
||||
// 全局监听器
|
||||
this.applicationContext.getBeanProvider(IMqttClientGlobalMessageListener.class).ifAvailable(clientCreator::globalMessageListener);
|
||||
// 自定义处理
|
||||
this.applicationContext.getBeanProvider(MqttClientCustomizer.class).ifAvailable(customizer -> customizer.customize(clientCreator));
|
||||
// 连接超时时间,如果没设置,改成 3s,减少因连不上卡顿时间
|
||||
Integer timeout = clientCreator.getTimeout();
|
||||
if (timeout == null) {
|
||||
clientCreator.timeout(3);
|
||||
}
|
||||
// 使用同步连接,不过如果连不上会卡一会
|
||||
client = clientCreator.connectSync();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
client.stop();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getOrder() {
|
||||
return Ordered.LOWEST_PRECEDENCE;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* 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.spring.client.annotation;
|
||||
|
||||
import org.dromara.mica.mqtt.spring.client.MqttClientRegistrar;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* @author ChangJin Wei (魏昌进)
|
||||
*/
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.TYPE)
|
||||
@Documented
|
||||
@Import(MqttClientRegistrar.class)
|
||||
public @interface EnableMqttClients {
|
||||
|
||||
String[] basePackages() default {};
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* 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.spring.client.annotation;
|
||||
|
||||
import org.dromara.mica.mqtt.spring.client.MqttClientTemplate;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* @author ChangJin Wei (魏昌进)
|
||||
*/
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.TYPE)
|
||||
@Documented
|
||||
public @interface MqttClient {
|
||||
|
||||
/**
|
||||
* 指定要使用的 MqttClientTemplate Bean
|
||||
*/
|
||||
String clientBean() default MqttClientTemplate.DEFAULT_CLIENT_TEMPLATE_BEAN;
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
/*
|
||||
* 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.spring.client.config;
|
||||
|
||||
import org.dromara.mica.mqtt.codec.message.builder.MqttTopicSubscription;
|
||||
import org.dromara.mica.mqtt.core.client.IMqttClientConnectListener;
|
||||
import org.dromara.mica.mqtt.core.client.MqttClient;
|
||||
import org.dromara.mica.mqtt.core.client.MqttClientCreator;
|
||||
import org.dromara.mica.mqtt.core.deserialize.MqttDeserializer;
|
||||
import org.dromara.mica.mqtt.core.deserialize.MqttJsonDeserializer;
|
||||
import org.dromara.mica.mqtt.spring.client.MqttClientSubscribeDetector;
|
||||
import org.dromara.mica.mqtt.spring.client.MqttClientSubscribeLazyFilter;
|
||||
import org.dromara.mica.mqtt.spring.client.MqttClientTemplate;
|
||||
import org.dromara.mica.mqtt.spring.client.event.SpringEventMqttClientConnectListener;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.tio.core.ssl.SSLEngineCustomizer;
|
||||
import org.tio.core.ssl.SslConfig;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* mqtt client 配置
|
||||
*
|
||||
* @author L.cm
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnProperty(
|
||||
prefix = MqttClientProperties.PREFIX,
|
||||
name = "enabled",
|
||||
havingValue = "true",
|
||||
matchIfMissing = true
|
||||
)
|
||||
@EnableConfigurationProperties(MqttClientProperties.class)
|
||||
public class MqttClientConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public MqttDeserializer mqttDeserializer() {
|
||||
return new MqttJsonDeserializer();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public IMqttClientConnectListener springEventMqttClientConnectListener(ApplicationEventPublisher eventPublisher) {
|
||||
return new SpringEventMqttClientConnectListener(eventPublisher);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public MqttClientCreator mqttClientCreator(MqttClientProperties properties, ObjectProvider<SSLEngineCustomizer> sslCustomizers) {
|
||||
MqttClientCreator clientCreator = MqttClient.create()
|
||||
.name(properties.getName())
|
||||
.ip(properties.getIp())
|
||||
.port(properties.getPort())
|
||||
.username(properties.getUsername())
|
||||
.password(properties.getPassword())
|
||||
.clientId(properties.getClientId())
|
||||
.bindIp(properties.getBindIp())
|
||||
.bindNetworkInterface(properties.getBindNetworkInterface())
|
||||
.readBufferSize((int) properties.getReadBufferSize().toBytes())
|
||||
.maxBytesInMessage((int) properties.getMaxBytesInMessage().toBytes())
|
||||
.maxClientIdLength(properties.getMaxClientIdLength())
|
||||
.keepAliveSecs(properties.getKeepAliveSecs())
|
||||
.heartbeatMode(properties.getHeartbeatMode())
|
||||
.heartbeatTimeoutStrategy(properties.getHeartbeatTimeoutStrategy())
|
||||
.reconnect(properties.isReconnect())
|
||||
.reInterval(properties.getReInterval())
|
||||
.retryCount(properties.getRetryCount())
|
||||
.reSubscribeBatchSize(properties.getReSubscribeBatchSize())
|
||||
.version(properties.getVersion())
|
||||
.cleanStart(properties.isCleanStart())
|
||||
.sessionExpiryIntervalSecs(properties.getSessionExpiryIntervalSecs())
|
||||
.statEnable(properties.isStatEnable())
|
||||
.debug(properties.isDebug())
|
||||
.disconnectBeforeStop(properties.isDisconnectBeforeStop());
|
||||
Integer timeout = properties.getTimeout();
|
||||
if (timeout != null && timeout > 0) {
|
||||
clientCreator.timeout(timeout);
|
||||
}
|
||||
// mqtt 业务线程数
|
||||
Integer bizThreadPoolSize = properties.getBizThreadPoolSize();
|
||||
if (bizThreadPoolSize != null && bizThreadPoolSize > 0) {
|
||||
clientCreator.bizThreadPoolSize(bizThreadPoolSize);
|
||||
}
|
||||
// 开启 ssl
|
||||
MqttClientProperties.Ssl ssl = properties.getSsl();
|
||||
if (ssl.isEnabled()) {
|
||||
SslConfig sslConfig = SslConfig.forClient(ssl.getKeystorePath(), ssl.getKeystorePass(), ssl.getTruststorePath(), ssl.getTruststorePass());
|
||||
clientCreator.sslConfig(sslConfig);
|
||||
sslCustomizers.ifAvailable(sslConfig::setSslEngineCustomizer);
|
||||
}
|
||||
// 构造遗嘱消息
|
||||
MqttClientProperties.WillMessage willMessage = properties.getWillMessage();
|
||||
if (willMessage != null && StringUtils.hasText(willMessage.getTopic())) {
|
||||
clientCreator.willMessage(builder -> {
|
||||
builder.topic(willMessage.getTopic())
|
||||
.qos(willMessage.getQos())
|
||||
.retain(willMessage.isRetain());
|
||||
if (StringUtils.hasText(willMessage.getMessage())) {
|
||||
builder.messageText(willMessage.getMessage());
|
||||
}
|
||||
});
|
||||
}
|
||||
// 全局订阅
|
||||
List<MqttTopicSubscription> globalSubscribe = properties.getGlobalSubscribe();
|
||||
if (globalSubscribe != null && !globalSubscribe.isEmpty()) {
|
||||
clientCreator.globalSubscribe(globalSubscribe);
|
||||
}
|
||||
return clientCreator;
|
||||
}
|
||||
|
||||
@Bean(MqttClientTemplate.DEFAULT_CLIENT_TEMPLATE_BEAN)
|
||||
@ConditionalOnMissingBean(name = MqttClientTemplate.DEFAULT_CLIENT_TEMPLATE_BEAN)
|
||||
public MqttClientTemplate mqttClientTemplate(MqttClientCreator mqttClientCreator) {
|
||||
return new MqttClientTemplate(mqttClientCreator);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public static MqttClientSubscribeDetector mqttClientSubscribeDetector(ApplicationContext applicationContext) {
|
||||
return new MqttClientSubscribeDetector(applicationContext);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public MqttClientSubscribeLazyFilter mqttClientSubscribeLazyFilter() {
|
||||
return new MqttClientSubscribeLazyFilter();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
/*
|
||||
* 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.spring.client.config;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.dromara.mica.mqtt.codec.MqttConstant;
|
||||
import org.dromara.mica.mqtt.codec.MqttQoS;
|
||||
import org.dromara.mica.mqtt.codec.message.builder.MqttTopicSubscription;
|
||||
import org.dromara.mica.mqtt.codec.MqttVersion;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.util.unit.DataSize;
|
||||
import org.tio.client.task.HeartbeatTimeoutStrategy;
|
||||
import org.tio.core.task.HeartbeatMode;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* MqttClient 配置
|
||||
*
|
||||
* @author wsq(冷月宫主)
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
@ConfigurationProperties(MqttClientProperties.PREFIX)
|
||||
public class MqttClientProperties {
|
||||
|
||||
/**
|
||||
* 配置前缀
|
||||
*/
|
||||
public static final String PREFIX = "mqtt.client";
|
||||
/**
|
||||
* 是否启用,默认:true
|
||||
*/
|
||||
private boolean enabled = true;
|
||||
/**
|
||||
* 名称,默认:Mica-Mqtt-Client
|
||||
*/
|
||||
private String name = "Mica-Mqtt-Client";
|
||||
/**
|
||||
* 服务端 ip,默认:127.0.0.1
|
||||
*/
|
||||
private String ip = "127.0.0.1";
|
||||
/**
|
||||
* 端口,默认:1883
|
||||
*/
|
||||
private int port = 1883;
|
||||
/**
|
||||
* 用户名
|
||||
*/
|
||||
private String username;
|
||||
/**
|
||||
* 密码
|
||||
*/
|
||||
private String password;
|
||||
/**
|
||||
* 客户端ID
|
||||
*/
|
||||
private String clientId;
|
||||
/**
|
||||
* 超时时间,单位:秒,t-io 配置,可为 null
|
||||
*/
|
||||
private Integer timeout;
|
||||
/**
|
||||
* 绑定 ip,绑定网卡,用于多网卡,默认为 null
|
||||
*/
|
||||
private String bindIp;
|
||||
/**
|
||||
* 绑定网卡,网卡名称,和 bindIp 取其一
|
||||
*/
|
||||
private String bindNetworkInterface;
|
||||
/**
|
||||
* 接收数据的 buffer size,默认:8k
|
||||
*/
|
||||
private DataSize readBufferSize = DataSize.ofBytes(MqttConstant.DEFAULT_MAX_READ_BUFFER_SIZE);
|
||||
/**
|
||||
* 消息解析最大 bytes 长度,默认:10M
|
||||
*/
|
||||
private DataSize maxBytesInMessage = DataSize.ofBytes(MqttConstant.DEFAULT_MAX_BYTES_IN_MESSAGE);
|
||||
/**
|
||||
* mqtt 3.1 会校验此参数为 23,为了减少问题设置成了 64
|
||||
*/
|
||||
private int maxClientIdLength = MqttConstant.DEFAULT_MAX_CLIENT_ID_LENGTH;
|
||||
/**
|
||||
* Keep Alive (s)
|
||||
*/
|
||||
private int keepAliveSecs = 60;
|
||||
/**
|
||||
* 心跳模式,支持最后发送或接收心跳时间来计算心跳,默认:最后发送心跳的时间
|
||||
*/
|
||||
private HeartbeatMode heartbeatMode = HeartbeatMode.LAST_REQ;
|
||||
/**
|
||||
* 心跳超时策略,支持发送 PING 和 CLOSE 断开连接,默认:最大努力发送 PING
|
||||
*/
|
||||
private HeartbeatTimeoutStrategy heartbeatTimeoutStrategy = HeartbeatTimeoutStrategy.PING;
|
||||
/**
|
||||
* 自动重连
|
||||
*/
|
||||
private boolean reconnect = true;
|
||||
/**
|
||||
* 重连的间隔时间,单位毫秒,默认:5000
|
||||
*/
|
||||
private long reInterval = 5000;
|
||||
/**
|
||||
* 连续重连次数,当连续重连这么多次都失败时,不再重连。0和负数则一直重连
|
||||
*/
|
||||
private int retryCount = 0;
|
||||
/**
|
||||
* 重连,重新订阅一个批次大小,默认:20
|
||||
*/
|
||||
private int reSubscribeBatchSize = 20;
|
||||
/**
|
||||
* mqtt 协议,默认:MQTT_5
|
||||
*/
|
||||
private MqttVersion version = MqttVersion.MQTT_5;
|
||||
/**
|
||||
* 清除会话
|
||||
* <p>
|
||||
* false 表示如果订阅的客户机断线了,那么要保存其要推送的消息,如果其重新连接时,则将这些消息推送。
|
||||
* true 表示消除,表示客户机是第一次连接,消息所以以前的连接信息。
|
||||
* </p>
|
||||
*/
|
||||
private boolean cleanStart = true;
|
||||
/**
|
||||
* 开启保留 session 时,session 的有效期,默认:0
|
||||
*/
|
||||
private int sessionExpiryIntervalSecs = 0;
|
||||
/**
|
||||
* 遗嘱消息
|
||||
*/
|
||||
private WillMessage willMessage;
|
||||
/**
|
||||
* 全局订阅
|
||||
*/
|
||||
private List<MqttTopicSubscription> globalSubscribe;
|
||||
/**
|
||||
* 是否开启监控,默认:false 不开启,节省内存
|
||||
*/
|
||||
private boolean statEnable = false;
|
||||
/**
|
||||
* debug
|
||||
*/
|
||||
private boolean debug = false;
|
||||
/**
|
||||
* mqtt 工作线程数,默认:2,如果消息量比较大,处理较慢,例如做 emqx 的转发消息处理,可以调大此参数
|
||||
*/
|
||||
private Integer bizThreadPoolSize;
|
||||
/**
|
||||
* 停止前是否发送 disconnect 消息,默认:true 不会触发遗嘱消息
|
||||
*/
|
||||
private boolean disconnectBeforeStop = true;
|
||||
/**
|
||||
* ssl 配置
|
||||
*/
|
||||
private Ssl ssl = new Ssl();
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public static class WillMessage {
|
||||
/**
|
||||
* 遗嘱消息 topic
|
||||
*/
|
||||
private String topic;
|
||||
/**
|
||||
* 遗嘱消息 qos,默认: qos0
|
||||
*/
|
||||
private MqttQoS qos = MqttQoS.QOS0;
|
||||
/**
|
||||
* 遗嘱消息 payload
|
||||
*/
|
||||
private String message;
|
||||
/**
|
||||
* 遗嘱消息保留标识符,默认: false
|
||||
*/
|
||||
private boolean retain = false;
|
||||
}
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public static class Ssl {
|
||||
/**
|
||||
* 启用 ssl
|
||||
*/
|
||||
private boolean enabled = false;
|
||||
/**
|
||||
* keystore 证书路径
|
||||
*/
|
||||
private String keystorePath;
|
||||
/**
|
||||
* keystore 密码
|
||||
*/
|
||||
private String keystorePass;
|
||||
/**
|
||||
* truststore 证书路径
|
||||
*/
|
||||
private String truststorePath;
|
||||
/**
|
||||
* truststore 密码
|
||||
*/
|
||||
private String truststorePass;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/*
|
||||
* 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.spring.client.event;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.tio.core.ChannelContext;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* mqtt 客户端连接成功事件
|
||||
*
|
||||
* @author L.cm
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class MqttConnectedEvent implements Serializable {
|
||||
|
||||
/**
|
||||
* context
|
||||
*/
|
||||
private ChannelContext context;
|
||||
/**
|
||||
* 是否重连
|
||||
*/
|
||||
private boolean isReconnect;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* 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.spring.client.event;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.tio.core.ChannelContext;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* mqtt 客户端断开连接事件
|
||||
*
|
||||
* @author L.cm
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class MqttDisconnectEvent implements Serializable {
|
||||
|
||||
/**
|
||||
* context
|
||||
*/
|
||||
private ChannelContext context;
|
||||
/**
|
||||
* 断开原因
|
||||
*/
|
||||
private String reason;
|
||||
/**
|
||||
* 是否删除连接
|
||||
*/
|
||||
private boolean isRemove;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
/*
|
||||
* 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.spring.client.event;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.dromara.mica.mqtt.core.client.IMqttClientConnectListener;
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
import org.tio.core.ChannelContext;
|
||||
|
||||
/**
|
||||
* spring event mqtt client 连接监听
|
||||
*
|
||||
* @author L.cm
|
||||
*/
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class SpringEventMqttClientConnectListener implements IMqttClientConnectListener {
|
||||
private final ApplicationEventPublisher eventPublisher;
|
||||
|
||||
@Override
|
||||
public void onConnected(ChannelContext context, boolean isReconnect) {
|
||||
if (isReconnect) {
|
||||
log.info("重连 mqtt 服务器重连成功...");
|
||||
} else {
|
||||
log.info("连接 mqtt 服务器成功...");
|
||||
}
|
||||
eventPublisher.publishEvent(new MqttConnectedEvent(context, isReconnect));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisconnect(ChannelContext context, Throwable throwable, String remark, boolean isRemove) {
|
||||
String reason;
|
||||
if (throwable == null) {
|
||||
reason = remark;
|
||||
log.info("mqtt 链接断开 remark:{} isRemove:{}", remark, isRemove);
|
||||
} else {
|
||||
reason = remark + " Exception:" + throwable.getMessage();
|
||||
log.error("mqtt 链接断开 remark:{} isRemove:{}", remark, isRemove, throwable);
|
||||
}
|
||||
eventPublisher.publishEvent(new MqttDisconnectEvent(context, reason, isRemove));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
open module org.dromara.mica.mqtt.client.spring.boot.starter {
|
||||
requires lombok;
|
||||
requires spring.core;
|
||||
requires spring.context;
|
||||
requires spring.boot;
|
||||
requires spring.boot.autoconfigure;
|
||||
requires transitive org.dromara.mica.mqtt.client;
|
||||
exports org.dromara.mica.mqtt.spring.client;
|
||||
exports org.dromara.mica.mqtt.spring.client.annotation;
|
||||
exports org.dromara.mica.mqtt.spring.client.config;
|
||||
exports org.dromara.mica.mqtt.spring.client.event;
|
||||
}
|
||||
Reference in New Issue
Block a user