Avoid duplicate client creation, i cached the client,The client may be offline when sending the message, what should I do in this case?
AbstractMqttClient client = cacheClientFactory.get(properties.getClient());
if (Objects.nonNull(client)) {
log.debug("client:{} is state : {}. {}", client.getClientId(), client.getClient().getState(), client.getClient().getState().isConnectedOrReconnect());
if (client.getClient().getState().isConnectedOrReconnect()) {
((MqttV5Client) client).publish(data, properties).thenAccept(publishResult -> {
if (publishResult.getError().isPresent()) {
log.error("Send msg failed", publishResult.getError().get());
} else {
}
});
} else if (client.getClient().getState() == MqttClientState.CONNECTING) {
log.info("client:{} is connecting - {}", client.getClientId(), client.getClient().getState());
} else {
log.info("client:{} is not null,but current state is {},ready reconnect", client.getClientId(), client.getClient().getState());
cacheClientFactory.remove(properties.getClient());
doConnectAndPublish(data, properties, (MqttV5Client) client);
}
} else {
log.info("client:{} will be created for the first time.", properties.getClient());
// connect and publish
doConnectAndPublish(data, properties, (MqttV5Client) client);
}