与多个服务器uri自动重新连接

时间:2018-08-29 18:59:13

标签: paho

考虑下面的代码的情况。

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为true,它将连接到localhost或其他主机吗?

1 个答案:

答案 0 :(得分:1)

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

首先您访问the Github repository for Paho source code

然后,在搜索字段中输入setAutomaticReconnect

browser screenshot 1

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

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

private boolean automaticReconnect = false;

然后您再次搜索automaticReconnect字词:

browser screenshot 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);