当前位置:   article > 正文

springboot整合mqtt完美解决emqx客户端频繁断线问题_emqx经常断线

emqx经常断线

概述

在使用emqx开源版服务的过程中,发现生产环境连接经常因为各种原因频繁断开,
本文将介绍mqtt5.0客户端的使用封装,并从空间冗余和时间冗余上完美解决客户端频繁掉线问题

引入依赖

        <dependency>
            <groupId>org.eclipse.paho</groupId>
            <artifactId>org.eclipse.paho.mqttv5.client</artifactId>
            <version>1.2.5</version>
        </dependency>
  • 1
  • 2
  • 3
  • 4
  • 5

外部化配置

emqx:
  broker-url: tcp://192.168.8.2:1883,tcp://192.168.8.3:1883
  client-id: test-route-msi
  username: admin
  password: public
  event-report-topic: "TestTopic"
#  event-report-topic: "test_topic"
  isCleanSession: false
  connectionTimeout: 0
  keepAliveInterval: 60
  maxInflight: 10000
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

配置类

包含空间冗余设计 提高可靠性 解决频繁断线问题

@Data
@Configuration
@ConfigurationProperties(prefix = "emqx")
@Slf4j
public class EmqxConfig {
   

    private String brokerUrl;

    private String clientId;

    private String username;

    private String password;

    private String eventReportTopic;

    private Boolean isCleanSession;

    private Integer connectionTimeout;
    private Integer keepAliveInterval;
    private Integer maxInflight;


    @Resource
    EmqClient emqClient;

    @PostConstruct
    public void init() {
   
		//支持集群多个节点 冗余设计 提供系统可靠性
        String url = RandomUtil.randomEle(brokerUrl.split(","));
        log.info("连接emqx的URL:{}", url);

        emqClient.init(url, clientId, username, password);

        MqttConnectionOptions options = new MqttConnectionOptions();

        //断线重连
        options.setAutomaticReconnect(true);
        options.setUserName(username);
        options.setPassword(password.getBytes());

        options.setCleanStart(isCleanSession);

        // 设置超时时间 单位为秒
        options.setConnectionTimeout(connectionTimeout);

        // 设置会话心跳时间 单位为秒 服务器会每隔1.5*10秒的时间向客户端发送个消息判断客户端是否在线,但这个方法并没有重连的机制
        options.setKeepAliveInterval(keepAliveInterval);

        boolean isConnected = emqClient.connect(options);

        //订阅接受上报事件主题
        if (isConnected) 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/748080
推荐阅读
相关标签
  

闽ICP备14008679号