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

AutoReconnect with multiple server uri's

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

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 为真,它会连接到本地主机还是其他主机?

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

首先访问the Github repository for Paho source code

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

这当然只是 public 的名字。您需要找到对应的私有成员。

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

private boolean automaticReconnect = false;

然后您执行另一次搜索,这次搜索 automaticReconnect 单词:

这会引导您找到 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);