* Vert.x *:如何处理同步代码

时间:2018-03-30 10:04:26

标签: java future vert.x

我有一种方法可以有条件地进行异步调用。以下是它的简化版本。如果条件是'我希望它返回满足了。

private void myMethod(RoutingContext routingContext, Handler<AsyncResult<AsyncReply>> handler) {
    //...
    if (condition) {
        // this does not work
        handler.handle(Future.succeededFuture(new AsyncReply(200, "")));
    }

    // here I do an async call and use the handler appropriately
    HttpClientRequest productRequest = client.getAbs(url, h -> h.bodyHandler(bh -> {
           // works  
           handler.handle(Future.succeededFuture(new AsyncReply(200, "")));
    }

}

我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

根据文档,您不能直接从事件循环调用阻塞操作,因为这会阻止它执行任何其他有用的工作。那你怎么能这样做呢?

通过调用executeBlocking来完成,指定要执行的阻塞代码和在执行阻塞代码时要异步调用的结果处理程序。

            vertx.executeBlocking(future -> {
              // Call some blocking API that takes a significant amount of time to return
              String result = someAPI.blockingMethod("hello");
              future.complete(result);
            }, res -> {
              System.out.println("The result is: " + res.result());
            });

答案 1 :(得分:1)

It turned out I was missing the basics of async programming..

It suffices to 'return' after the Successful Future is handed.

Otherwise, the code continues to execute and makes the call anyway.

private void myMethod(RoutingContext routingContext, Handler<AsyncResult<AsyncReply>> handler) {
    //...
    if (condition) {
        // this does not work
        handler.handle(Future.succeededFuture(new AsyncReply(200, "")));
        return; // !!!!! 
    }

    // here I do an async call and use the handler appropriately
    HttpClientRequest productRequest = client.getAbs(url, h -> h.bodyHandler(bh -> {
           // works  
           handler.handle(Future.succeededFuture(new AsyncReply(200, "")));
    }

}