Vertx 3 是否支持 CompletableFuture?

Does Vertx 3 support CompletableFuture?

我想使用 vertx 和 CompletableFuture 开发我的应用程序 promise 风格非常适合这个目的,但是 JVM 在 CompletableFuture 的后台使用 fork/join,这可能会破坏 Vertx 线程安全。

您有任何想法或在您的项目中使用过此功能吗?

是的,这是一个例子http://qrman.github.io/posts/2015/08/28/callback_hell_completablefuture_ftw/

但我认为 JavaRx 是更好的解决方案,因为它作为第一个 class 公民受到 vert.x http://vertx.io/docs/vertx-rx/java/

的支持

还有https://github.com/cescoffier/vertx-completable-future。来自自述文件:

This project provides the Completable Future API but enforces the Vert.x threading model:

  • When using xAsync methods (without executor), the callbacks are called on the Vert.x context
  • When using non-async, it uses the caller thread. If it's a Vert.x thread the same thread is used. If not called from a Vert.x thread, it still uses the caller thread
  • When using xAsync methods with an Executor parameter, this executor is used to execute the callback (does not enforce the Vert.x thread system)

不过还没用过

从技术上看,它始终可以对不受 Vertx 管理的其他线程执行异步操作,并且 return 结果将由 Vertx 管理的线程使用。关键是在使用 vertx.getOrCreateContext() 开始异步操作之前获得 Context before,然后在准备就绪时将其用于 return 结果。

假设您有某种 Handler<AsyncResult<>>,这可以是示例代码:

public void doAsyncThing(String someParam, String otherParam, Handler<AsyncResult<Void>> resultHandler) {
    Context vertxContext = vertx.getOrCreateContext();
    CompletableFuture<Void> future = 
        someOperatinThatTriggersAsync(someParam, otherParam)
            .handleAsync((unused, throwable) -> {
                vertxContext.runOnContext(unused1 -> {
                    if (throwable == null) {
                      responseHandler.handle(Future.succeededFuture());
                    } else {
                      responseHandler.handle(Future.failedFuture(throwable));
                    }
                });
                return null;
          });
}