Kotlin coroutines 和“挂起函数”使程序员可以很容易地等待 I/O 的结果而无需停止线程(在 I/O 完成之前线程有其他工作要做)。
jOOQ 是一种 Java 优先的产品,用于以类型安全的方式编写和执行 SQL,但它本身并没有明确使用 Kotlin 协程。
是否可以从 Kotlin 协同例程范围调用 jOOQ 以获得易于编写和线程高效甚至在 IO 期间的好处?
suspend fun myQuery() {
return dsl.select()
// .etc()
.fetch() // <- could this be a 'suspend' call?
}
最佳答案
答:是的。
因为
org.jooq.ResultQuery<R extends Record>
有一个 @NotNull CompletionStage<Result<R>> fetchAsync()
` 挂接到 Java (JDK 8+) 机制的“ future ”方法。
和
kotlinx-coroutines-jdk8
提供一个 bunch of extension methods用于在 Kotlin 挂起函数和 JDK 8+ futures 之间进行适配。
因此我们可以:
import kotlinx.coroutines.future.await
...
suspend fun myQuery() {
return dsl.select()
//.etc()
.fetchAsync()
.await() // <- IS a suspending call !!!
}
需要注意的是有一堆重载fetchX()
ResultQuery
上的方法它为同步调用提供了很多实用程序,但对于 fetchAsync()
它们并没有类似地过载.这就是 Kotlin 程序员可能希望熟悉 Java future 机制的地方:任何类型的操作都可以使用 thenApply {}
method 异步完成。在 CompletionStage<T>
.例如映射结果:
suspend fun myQuery() {
return dsl.select()
//.etc()
.fetchAsync()
.thenApply { it.map(mapping(::Film)) } // <- done as part of the 'suspend'
.await()
}
虽然暂停之后再做应该没问题:
suspend fun myQuery() {
val records = dsl.select()
//.etc()
.fetchAsync()
.await()
return records.map(mapping(::Film))
}
关于kotlin-coroutines - jOOQ 是否与 Kotlin 协程配合得很好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68915965/