简体   繁体   English

Vert.x 3,请求处理程序POST,异步CompletionStage或CompletableFuture

[英]Vert.x 3, request handler POST, async CompletionStage or CompletableFuture

class MyVerticle extends AbstractVerticle {

 void start ...

   router.get("/api/v1/mypostcall").handler(routingContext -> {
       ...
       // I have existing async code, which I want to plug here.
       CompletionStage<String> jsonCompletable = ...

       // How do I respond using the CompletionStage (or CompletableFuture) to VertX
       // so it does not block here ?
    }

I have also read about the vert.x context , but the routingContext is something else and the example is about unit tests ... Do you have any example of integration between Java CompletionStage or must I use RxJava ? 我还阅读了有关vert.x上下文的信息 ,但是routingContext是其他内容,并且该示例是关于单元测试的。...您是否有Java CompletionStage之间集成的任何示例,还是必须使用RxJava?

There nothing special with CompletableFuture . CompletableFuture没有什么特别的。 It's like any async api. 就像任何异步api一样。 Simple example, that follows vertx thread model. 一个简单的例子,遵循vertx线程模型。 Computation happens on some computational context, and result writes on vertx event loop: 计算发生在某些计算上下文中,结果写在vertx事件循环上:

public static CompletionStage<String> calculateAsync()  {
    CompletableFuture<String> completableFuture = new CompletableFuture<>();
    Executors.newCachedThreadPool().submit(() -> {
        Thread.sleep(5000);
        completableFuture.complete("Hello");
        return null;
    });
    return completableFuture;
}

public static void main(String[] args) {
    Vertx vertx = Vertx.vertx();
    Router router = Router.router(vertx);
    Router.router(vertx).get("/api").handler(ctx -> {
        calculateAsync().whenComplete((result, e) -> vertx.runOnContext(none -> {
            ctx.response().end(result);
        }));

    });
    vertx.createHttpServer().requestHandler(router::accept).listen(8080);
}

If all your stages are non-blocking and follow the Vert.x threading model (meaning always use the event loop), just use the "handle" method from your completable future in which you write the response (routingContext.response().end(...)) or report a failure. 如果您的所有阶段都是非阻塞的,并且遵循Vert.x线程模型(意味着始终使用事件循环),则只需使用可完成的将来中的“ handle”方法即可在其中编写响应(routingContext.response()。end (...))或报告失败。

If you are integrating stages not following the Vert.x threading model, you can use https://github.com/cescoffier/vertx-completable-future that provides a way to always call the stage in the "right" thread. 如果要集成不遵循Vert.x线程模型的阶段,则可以使用https://github.com/cescoffier/vertx-completable-future ,该方法提供了始终在“正确”线程中调用阶段的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM