我正在为我的一些应用程序使用MQTT客户端Java库,我认为我正在以不好的方式重新连接到代理。现在,我有一个处理MQTT操作的类,如connect,disconnect,publish和subscribe。
public class MqttConnection {
private static final String BROKER_ADDRESS = Preferences.getProperty("mqtt-address");
private static final String BROKER_PORT = Preferences.getProperty("mqtt-port");
private static final String BROKER_URI = "tcp://" + BROKER_ADDRESS + ":" + BROKER_PORT;
private static final String VHOST = Preferences.getProperty("mqtt-vhost");
private static final String USERNAME = Preferences.getProperty("mqtt-username");
private static final String PASSWORD = Preferences.getProperty("mqtt-password");
private static MqttClient client;
private static final Logger logger = LogManager.getLogger(MqttConnection.class);
static {
try {
client = new MqttClient(BROKER_URI, MqttClient.generateClientId());
} catch (MqttException ex) {
logger.fatal(ex);
}
client.setCallback(new MqttCallback() {
@Override
public void connectionLost(Throwable thrwbl) {
logger.info("MQTT : Perte de connexion...");
MqttConnection.start();
}
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
// CODE HERE
}
@Override
public void deliveryComplete(IMqttDeliveryToken imdt) { }
});
}
public static void start() {
connect();
}
private static void connect() {
if (!client.isConnected()) {
try {
if (Preferences.getProperty("mqtt-isauth").equalsIgnoreCase("true")) {
MqttConnectOptions options = new MqttConnectOptions();
String username = (VHOST.equals("")) ? USERNAME : VHOST + ":" + USERNAME;
options.setUserName(username);
options.setPassword(PASSWORD.toCharArray());
client.connect(options);
} else {
client.connect();
}
logger.info("MQTT : Connecté au broker.");
} catch (MqttException ex) {
logger.fatal(ex);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
logger.fatal(e);
}
connect();
}
}
}
private static void subscribe() {
if (client.isConnected()) {
try {
client.subscribe("+/SWI1");
} catch (MqttException e) {
logger.fatal(e);
}
}
}
}
但它似乎在尝试重新连接时打开了许多连接,并使代理错误。 重新连接到MQTT代理的最佳方法是什么?
答案 0 :(得分:0)
您可以使用MqttConnectOptions.setAutomaticReconnect(true)
启用自动重新连接。