有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java*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) 个答案

  1. # 1 楼答案

    结果是我错过了异步编程的基础知识

    在成功的未来到来后,“回归”就足够了

    否则,代码将继续执行并进行调用

    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, "")));
        }
    
    }
    
  2. # 2 楼答案

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

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

                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());
                });