Coroutines
Kotlin Coroutines 是轻量级线程,允许强制性地编写非阻塞代码。在语言方面,suspend 函数为异步操作提供了一个抽象,而 kotlinx.coroutines 在库方面提供了 async { } 等函数和 Flow 等类型。
Spring Data 模块为以下范围内的协程提供支持:
Dependencies
当 kotlinx-coroutines-core、kotlinx-coroutines-reactive 和 kotlinx-coroutines-reactor 依赖项在 classpath 中时,协程支持处于启用状态:
<dependency>
<groupId>org.jetbrains.kotlinx</groupId>
<artifactId>kotlinx-coroutines-core</artifactId>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlinx</groupId>
<artifactId>kotlinx-coroutines-reactive</artifactId>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlinx</groupId>
<artifactId>kotlinx-coroutines-reactor</artifactId>
</dependency>
|
支持版本 |
How Reactive translates to Coroutines?
对于返回值,从 Reactive 到协程 API 的转换如下所示:
-
fun handler(): Mono<Void>变成suspend fun handler() -
fun handler(): Mono<T>根据Mono是否可以为空(以静态类型更强的优点)变成suspend fun handler(): T或suspend fun handler(): T? -
fun handler(): Flux<T>变成fun handler(): Flow<T>
Flow 是 Coroutines 世界中 Flux 的等价物,适用于热流或冷流、有限流或无限流,具有以下主要区别:
-
Flow是面向推送的,而Flux是面向推送-拉取的混合型 -
反压通过挂起函数实现
-
Flow仅有 single suspendingcollectmethod,并且操作符以 extensions 的形式实现 -
扩展允许将自定义操作符添加到
Flow -
收集操作是挂起函数
-
link:https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/map.html[
map操作符由于采用挂起函数参数,因此支持异步操作(无需flatMap)
阅读有关 Going Reactive with Spring, Coroutines and Kotlin Flow 的博客文章以获得更多详细信息,包括如何使用 Coroutines 并发运行代码。
Repositories
以下是协程存储库的一个示例:
interface CoroutineRepository : CoroutineCrudRepository<User, String> {
suspend fun findOne(id: String): User
fun findByFirstname(firstname: String): Flow<User>
suspend fun findAllByFirstname(id: String): List<User>
}
协程存储库建立在响应式存储库上,以通过 Kotlin 的协程公开非阻塞数据访问本质。协程存储库上的方法可以由查询方法或自定义实现支持。如果自定义方法为 suspend,调用自定义实现方法会将协程调用传播到实际实现方法,而不要求实现方法返回响应式类型,如 Mono 或 Flux。
请注意,根据方法声明,协程上下文可能可用或不可用。要保留对上下文的访问,请使用 suspend 声明你的方法或返回能启用上下文传播的类型,如 Flow。
-
suspend fun findOne(id: String): User:通过挂起,一次同步地检索数据。 -
fun findByFirstname(firstname: String): Flow<User>:检索数据流。Flow是热切创建的,而数据是在Flow交互 (Flow.collect(…)) 时获取的。 -
fun getUser(): User:一次检索数据 blocking the thread,且没有上下文传播。应避免这种情况。
|
只有当存储库扩展 |