Eclipse Paho自动重新连接配置

时间:2017-06-07 05:40:17

标签: mqtt paho

如java客户端automaticReconnect功能的文档中所述:

  

客户端断开后,客户端将尝试   以越来越大的时间间隔连接。从1秒开始,   每次失败的尝试加倍,最多2分钟。

但它提出了一些关于客户行为的问题:

  1. 限制2分钟后,客户会继续尝试无限期连接吗? 因为我无法找到任何其他参数来控制此迭代。

  2. 有没有办法配置这段时间?

1 个答案:

答案 0 :(得分:1)

查看MqttAsyncClient.java源代码(我已删除了以下几行):

/**
 * Attempts to reconnect the client to the server.
 * If successful it will make sure that there are no further
 * reconnects scheduled. However if the connect fails, the delay will double
 * up to 128 seconds and will re-schedule the reconnect for after the delay.
 * 
 * Any thrown exceptions are logged but not acted upon as it is assumed that 
 * they are being thrown due to the server being offline and so reconnect
 * attempts will continue.
 */
private void attemptReconnect(){
    final String methodName = "attemptReconnect";   
    //@Trace 500=Attempting to reconnect client: {0}
    log.fine(CLASS_NAME, methodName, "500", new Object[]{this.clientId});

    connect(this.connOpts, this.userContext,new IMqttActionListener() {

        public void onSuccess(IMqttToken asyncActionToken) {
            //@Trace 501=Automatic Reconnect Successful: {0}
            log.fine(CLASS_NAME, methodName, "501", new Object[]{asyncActionToken.getClient().getClientId()});
            comms.setRestingState(false);
            stopReconnectCycle();
        }

        public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
            //@Trace 502=Automatic Reconnect failed, rescheduling: {0}
            log.fine(CLASS_NAME, methodName, "502", new Object[]{asyncActionToken.getClient().getClientId()});
            if(reconnectDelay < 128000){
                reconnectDelay = reconnectDelay * 2;
            }
            rescheduleReconnectCycle(reconnectDelay);
        }
    });
}

因此重新连接延迟将为:1, 2, 4, 8, 16, 32, 64, 128, 128, 128, 128, ...