【问题标题】:How to convert a CompletableFuture to a Vert.X Future如何将 CompletableFuture 转换为 Vert.X Future
【发布时间】:2022-01-12 20:46:15
【问题描述】:

我正在尝试在协程中使用 vertx 反应式 sql 客户端执行数据库事务。 不知何故,我无法弄清楚如何将 CompletableFuture 转换为所需的 io.vertx.core.Future 类型。是否有任何辅助方法或扩展可以轻松做到这一点?

val client : PgPool
... 

suspend fun someServiceFunction () {
    coroutineScope {
        client.withTransaction { connection ->
            val completableFuture = async {
                repository.save(connection, requestDTO)  //This is a suspend function
            }.asCompletableFuture()

            //Return type has to be a io.vertx.core.Future
            //How can I transform the completableFuture to it ?
        }
    }
}

感谢您的帮助!

【问题讨论】:

    标签: kotlin kotlin-coroutines vert.x vert.x-webclient


    【解决方案1】:

    Vert.x Future 有转换方法:

    future = Future.fromCompletionStage(completionStage, vertxContext)
    

    【讨论】:

    • 这就是我要寻找的!非常感谢您
    【解决方案2】:

    我从asCompletableFuture() 的代码中对此进行了改编,以用作替代方案。免责声明:我没有使用 Vert.x,也没有对此进行测试。

    fun <T> Deferred<T>.asVertxFuture(): Future<T> {
        val promise = Promise.promise<T>()
        invokeOnCompletion {
            try {
                promise.complete(getCompleted())
            }  catch (t: Throwable) {
                promise.fail(t)
            }
        }
        return promise.future()
            .onComplete { result ->
                cancel(result.cause()?.let {
                    it as? CancellationException ?: CancellationException("Future was completed exceptionally", it)
                })
            }
    }
    

    我想知道在 Vert.x 中混合协程是否会损害性能,因为您没有使用 Vert.x 线程池。也许你可以创建一个Dispatchers.Vertx 借用它的线程池。

    【讨论】:

    • 那会是什么样子?
    • @AhmetKazaman 我用过很多 Vert.x,但我没有用过 Kotlin,所以我不知道答案。我猜想我链接到的页面上的文档将为更熟悉 Kotlin 的人提供足够的指导来找出答案(我怀疑你根本不需要 CompletableFuture 来做 OP 是尝试做),但我真的不确定!
    • 是的,我认为您只需要在某些情况下使用上述功能。如果您在项目中使用协程而不使用遗留代码或需要使用 Future 的 API,则直接传递 Kotlin Deferred 或简单地使用挂起函数会更自然。在使用协程处理 Vert.x 时,我会使用链接的调度程序 @dano。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-20
    • 2017-01-27
    • 2021-07-22
    相关资源
    最近更新 更多