繁体   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 ?
    }

我还阅读了有关vert.x上下文的信息 ,但是routingContext是其他内容,并且该示例是关于单元测试的。...您是否有Java CompletionStage之间集成的任何示例,还是必须使用RxJava?

CompletableFuture没有什么特别的。 就像任何异步api一样。 一个简单的例子,遵循vertx线程模型。 计算发生在某些计算上下文中,结果写在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);
}

如果您的所有阶段都是非阻塞的,并且遵循Vert.x线程模型(意味着始终使用事件循环),则只需使用可完成的将来中的“ handle”方法即可在其中编写响应(routingContext.response()。end (...))或报告失败。

如果要集成不遵循Vert.x线程模型的阶段,则可以使用https://github.com/cescoffier/vertx-completable-future ,该方法提供了始终在“正确”线程中调用阶段的方法。

暂无
暂无

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

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