first commit
This commit is contained in:
@@ -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