我正在JVM中使用大量IO启动一个新项目。在某个时候,我必须将一些东西保存在Mongo数据库中。我的想法是对Kotlin协程使用非阻塞方法。
我知道Mongo有官方的React Streams驱动程序,支持看起来不错。但是在这种情况下,我将需要在流和协程之间“创建桥梁”。我的问题是关于这一点的:有人知道更好或更简单的方法吗?
看看KMongo project。 has协程支持:
import org.litote.kmongo.reactivestreams.* //NEEDED! import KMongo reactivestreams extensions
import org.litote.kmongo.coroutine.* //NEEDED! import KMongo coroutine extensions
data class Jedi(val name: String, val age: Int)
val client = KMongo.createClient().coroutine //use coroutine extension
val database = client.getDatabase("test") //normal java driver usage
val col = database.getCollection<Jedi>() //KMongo extension method
//async now
runBlocking {
col.insertOne(Jedi("Luke Skywalker", 19))
val yoda : Jedi? = col.findOne(Jedi::name eq "Yoda")
(...)
}