JOOQ能很好地处理Kotlin协程程序吗? [英] Does jOOQ play nicely with Kotlin coroutines?
本文介绍了JOOQ能很好地处理Kotlin协程程序吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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?
}
推荐答案
A:是的。
因为
org.jooq.ResultQuery<R extends Record>
有一个@NotNull CompletionStage<Result<R>> fetchAsync()
`方法,该方法挂接到Java(JDK 8+)机制中以用于‘Futures’。
和
kotlinx-coroutines-jdk8
提供了一个bunch of extension methods用于在Kotlin挂起函数和JDK 8+期货之间进行适配。
因此我们可以:
import kotlinx.coroutines.future.await
...
suspend fun myQuery() {
return dsl.select()
//.etc()
.fetchAsync()
.await() // <- IS a suspending call !!!
}
应该注意,ResultQuery
上有一组重载的fetchX()
方法,它们为同步调用提供了许多实用程序,但fetchAsync()
没有类似的重载。这就是Kotlin程序员可能希望熟悉Java期货机制的地方:任何类型的操作都可以使用thenApply {}
methodonCompletionStage<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))
}
这篇关于JOOQ能很好地处理Kotlin协程程序吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文