我正在嘗試在協程中使用 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 ?
}
}
}
感謝您的幫助 !
uj5u.com熱心網友回復:
我從代碼中改編了它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借用其執行緒池的方法。
uj5u.com熱心網友回復:
Vert.x Future 有一個轉換方法:
future = Future.fromCompletionStage(completionStage, vertxContext)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/375952.html
標籤:科特林 kotlin 协程 顶点.x vert.x-webclient
