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();
// 连接成功!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值