paho - 使用多个服务器 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 源代码的 Github 存储库。
然后进入setAutomaticReconnect
搜索栏:
这当然只是公共名称。您需要发现相应的私人成员。
在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);
推荐阅读
- scala - 无法读取 Hive 中的特定表
- algorithm - 随机分配数量
- java - 如何从 URL 解析 json 数据并将其添加到自动完成搜索视图
- javascript - 我有一个简单的 HTML 表单:个性测验,有一组单选按钮的 Javascript 功能。如何在 PHP 文件中分析它
- javascript - 使用“深度”数组对 useState 做出反应,而不是重新渲染组件
- php - 使用 PHP 数组的灵活列类
- node.js - 总是返回 401 Unauthorized in passport-jwt
- node.js - 有没有办法在vue中引用图像?
- javascript - 如何将 application/vnd.ms-excel 与非拉丁语言一起使用?
- python - 如何让 python 从列表中返回尽可能多的谜语