首页 > 解决方案 > 使用多个服务器 uri 自动重新连接

问题描述

考虑我有以下代码的场景。

MqttConnectOptions connOpt = new MqttConnectOptions();
connOpt.setServerURIs(new String[]{"tcp://localhost:1883", "tcp://some-other-host:1883"});
connOpt.setAutomaticReconnect(true);
client.setCallback( new TemperatureSubscriber() );
client.connect(connOpt);

所以当我说连接时,它连接到本地主机。然后我失去了连接,由于任何原因。那么此时,由于 automaticReconnect 为真,它会连接到 localhost 还是 some-other-host ?

标签: paho

解决方案


让我展示如何自己找到这样的答案 -

首先,您访问Paho 源代码的 Github 存储库

然后进入setAutomaticReconnect搜索栏:

浏览器截图1

这当然只是公共名称。您需要发现相应的私人成员。

MqttConnectOptions.java中,您可以使用非常简单的代码找到该成员:

private boolean automaticReconnect = false;

然后你执行另一个搜索,这次是这个automaticReconnect词:

浏览器截图2

这将引导您找到MqttAsyncClient.java文件中的提示 -

    // Insert our own callback to iterate through the URIs till the connect
    // succeeds
    MqttToken userToken = new MqttToken(getClientId());
    ConnectActionListener connectActionListener = new ConnectActionListener(this, persistence, comms, options,
            userToken, userContext, callback, reconnecting);
    userToken.setActionCallback(connectActionListener);
    userToken.setUserContext(this);

最后,在ConnectActionListener.java文件中,您可以确认 URL 一个接一个地被尝试:

  /**
   * The connect failed, so try the next URI on the list.
   * If there are no more URIs, then fail the overall connect. 
   * 
   * @param token the {@link IMqttToken} from the failed connection attempt
   * @param exception the {@link Throwable} exception from the failed connection attempt
   */
  public void onFailure(IMqttToken token, Throwable exception) {

    int numberOfURIs = comms.getNetworkModules().length;
int index = comms.getNetworkModuleIndex();
    ...
    ...
 comms.setNetworkModuleIndex(index + 1);

推荐阅读