mica-mqtt动态初始化clientId的办法
【代码】mica-mqtt动态初始化clientId的办法。
·
1.pom
<!--mqtt-->
<dependency>
<groupId>net.dreamlu</groupId>
<artifactId>mica-mqtt-client</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>net.dreamlu</groupId>
<artifactId>mica-mqtt-client-spring-boot-starter</artifactId>
<version>2.2.4</version>
</dependency>
2.yml
mqtt:
client:
enabled: false
ip: 127.0.0.1 # 连接的服务端 ip ,默认:127.0.0.1
port: 1883 # 端口:默认:1883
name: Mica-Mqtt-Client # 名称,默认:Mica-Mqtt-Client
# clientId: xxx # 客户端Id(非常重要,一般为设备 sn,不可重复)
user-name: xxx # 认证的用户名
password: xxx # 认证的密码
timeout: 5 # 超时时间,单位:秒,默认:5秒
reconnect: true # 是否重连,默认:true
re-interval: 5000 # 重连时间,默认 5000 毫秒
version: mqtt_3_1_1 # mqtt 协议版本,可选 MQTT_3_1、mqtt_3_1_1、mqtt_5,默认:mqtt_3_1_1
read-buffer-size: 8KB # 接收数据的 buffer size,默认:8k
max-bytes-in-message: 10MB # 消息解析最大 bytes 长度,默认:10M
buffer-allocator: heap # 堆内存和堆外内存,默认:堆内存
keep-alive-secs: 60 # keep-alive 时间,单位:秒
clean-session: true # mqtt clean session,默认:true
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 密码
3.代码
import net.dreamlu.iot.mqtt.core.client.IMqttClientConnectListener;
import net.dreamlu.iot.mqtt.core.client.IMqttClientSession;
import net.dreamlu.iot.mqtt.core.client.MqttClient;
import net.dreamlu.iot.mqtt.core.client.MqttClientCreator;
import net.dreamlu.iot.mqtt.spring.client.MqttClientCustomizer;
import net.dreamlu.iot.mqtt.spring.client.MqttClientSubscribeDetector;
import net.dreamlu.iot.mqtt.spring.client.MqttClientTemplate;
import net.dreamlu.iot.mqtt.spring.client.config.MqttClientProperties;
import net.dreamlu.iot.mqtt.spring.client.event.SpringEventMqttClientConnectListener;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
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 javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
@Configuration(
proxyBeanMethods = false
)
@EnableConfigurationProperties({MqttClientProperties.class})
@ConfigurationProperties("mqtt.client")
public class MqttConfig {
public MqttConfig() {
}
@Bean
@ConditionalOnMissingBean
public IMqttClientConnectListener springEventMqttClientConnectListener(ApplicationEventPublisher eventPublisher) {
return new SpringEventMqttClientConnectListener(eventPublisher);
}
@Bean
public MqttClientCreator mqttClientCreator(MqttClientProperties properties, ObjectProvider<IMqttClientSession> clientSessionObjectProvider) {
MqttClientCreator clientCreator = MqttClient.create()
.name(properties.getName())
.ip(properties.getIp())
.port(properties.getPort())
.username(properties.getUserName())
.password(properties.getPassword())
.clientId("这里填入动态clientId") //这里填入动态clientId
.readBufferSize((int)properties.getReadBufferSize().toBytes())
.maxBytesInMessage((int)properties.getMaxBytesInMessage().toBytes())
.maxClientIdLength(properties.getMaxClientIdLength())
.keepAliveSecs(properties.getKeepAliveSecs())
.reconnect(properties.isReconnect())
.reInterval(properties.getReInterval())
.retryCount(properties.getRetryCount())
.reSubscribeBatchSize(properties.getReSubscribeBatchSize())
.version(properties.getVersion()).cleanSession(properties.isCleanSession())
.bufferAllocator(properties.getBufferAllocator()).statEnable(properties.isStatEnable());
Integer timeout = properties.getTimeout();
if (timeout != null && timeout > 0) {
clientCreator.timeout(timeout);
}
if (properties.isDebug()) {
clientCreator.debug();
}
MqttClientProperties.Ssl ssl = properties.getSsl();
if (ssl.isEnabled()) {
clientCreator.useSsl(ssl.getKeystorePath(), ssl.getKeystorePass(), ssl.getTruststorePath(), ssl.getTruststorePass());
}
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.message(willMessage.getMessage().getBytes(StandardCharsets.UTF_8));
}
});
}
clientSessionObjectProvider.ifAvailable(clientCreator::clientSession);
return clientCreator;
}
@Bean({"mqttClientTemplate"})
public MqttClientTemplate mqttClientTemplate(MqttClientCreator mqttClientCreator, ObjectProvider<IMqttClientConnectListener> clientConnectListenerObjectProvider, ObjectProvider<MqttClientCustomizer> customizers) {
return new MqttClientTemplate(mqttClientCreator, clientConnectListenerObjectProvider, customizers);
}
@Bean
public MqttClientSubscribeDetector mqttClientSubscribeDetector(ApplicationContext applicationContext) {
return new MqttClientSubscribeDetector(applicationContext);
}
}
mqtt切换clientId 重新连接
// 重新绑定 mqtt客户端
mqttClientCreator.clientId(deviceId);
// 绑定完成 正在重连
mqttClientCreator.connect();
// 连接成功!
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐

所有评论(0)