如何在vert.x中创建MqttClient并在其他类或组件中重用?

时间:2018-09-27 06:10:39

标签: java mqtt vert.x

Fisrt,我想创建一个MqttClient并在其他类中重用,这就是我想做的

public class MqttClientUtil {
private static final Logger log = LoggerFactory.getLogger(MqttClientUtil.class);
private static final String BROKER_HOST = "localhost";
private static final int BROKER_PORT = 1883;
private static MqttClient mqttClient;

public static MqttClient getMqttClientUtil() {
    if (null == mqttClient) {
        mqttClient = MqttClient.create(Vertx.vertx())
            .connect(BROKER_PORT, BROKER_HOST, res -> {
                System.out.println(res);
            });
        return mqttClient;
    } else {
        return mqttClient;
    }
}

}

在这段代码中,我不会同时处理两个或多个线程以获取客户端。但这不起作用,似乎该线程在connect函数中被阻塞了。

正确的做法是什么?

1 个答案:

答案 0 :(得分:0)

如注释中所述,您可以阻止该方法,直到使用CountDownLatch将其连接起来为止:

public class MqttClientUtil {
    private static final Logger log = LoggerFactory.getLogger(MqttClientUtil.class);
    private static final String BROKER_HOST = "iot.eclipse.org";
    private static final int BROKER_PORT = 1883;
    private static MqttClient mqttClient;

    public static MqttClient getMqttClientUtil() {
        if (mqttClient == null) {
            CountDownLatch latch = new CountDownLatch(1);
            mqttClient = MqttClient.create(Vertx.vertx()).connect(BROKER_PORT, BROKER_HOST, res -> {
                if (res.succeeded()) System.out.println("connected");
                latch.countDown();
            });

            try { latch.await(10000, TimeUnit.MILLISECONDS); }
            catch (InterruptedException e) {
                e.printStackTrace();
                return null;
            }
        }

        return mqttClient;
    }
}