赞
踩
在使用emqx开源版服务的过程中,发现生产环境连接经常因为各种原因频繁断开,
本文将介绍mqtt5.0客户端的使用封装,并从空间冗余和时间冗余上完美解决客户端频繁掉线问题
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.mqttv5.client</artifactId>
<version>1.2.5</version>
</dependency>
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
包含空间冗余设计 提高可靠性 解决频繁断线问题
@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)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。