协程
Kotlin 协程 是一种可挂起的计算实例,允许以命令式的方式编写非阻塞代码。在语言层面,suspend
函数为异步操作提供了抽象,而在库层面,kotlinx.coroutines 提供了诸如 async { } 的函数以及 Flow 等类型。
Spring Data 模块在以下范围内提供了对协程的支持:
依赖项
当 kotlinx-coroutines-core
、kotlinx-coroutines-reactive
和 kotlinx-coroutines-reactor
依赖项在类路径中时,协程支持将被启用:
<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>
支持的版本为 1.3.0
及以上。
响应式如何转换为协程?
对于返回值,从 Reactive 到 Coroutines API 的转换如下:
-
fun handler(): Mono<Void>
变为suspend fun handler()
-
fun handler(): Mono<T>
变为suspend fun handler(): T
或suspend fun handler(): T?
,具体取决于Mono
是否可以为空(具有更静态类型的优势) -
fun handler(): Flux<T>
变为fun handler(): Flow<T>
Flow 是协程世界中的 Flux
等效物,适用于热流或冷流、有限或无限流,主要有以下区别:
-
Flow
是基于推送的,而Flux
是推送-拉取混合的 -
背压通过挂起函数实现
-
Flow
只有一个挂起的 collect 方法,操作符通过扩展函数实现 -
由于协程的存在,操作符很容易实现
-
扩展函数允许向
Flow
添加自定义操作符 -
收集操作是挂起函数
-
map 操作符支持异步操作(不需要
flatMap
),因为它接受一个挂起函数参数
阅读这篇博客文章 Going Reactive with Spring, Coroutines and Kotlin Flow 以了解更多细节,包括如何使用协程并发运行代码。
仓库
这是一个 Coroutines 仓库的示例:
interface CoroutineRepository : CoroutineCrudRepository<User, String> {
suspend fun findOne(id: String): User
fun findByFirstname(firstname: String): Flow<User>
suspend fun findAllByFirstname(id: String): List<User>
}
协程仓库(Coroutines repositories)是构建在响应式仓库(reactive repositories)之上的,旨在通过 Kotlin 的协程(Coroutines)来暴露数据访问的非阻塞特性。协程仓库中的方法可以通过查询方法或自定义实现来支持。调用自定义实现方法时,如果该自定义方法是 suspend
可挂起的,协程调用会直接传播到实际的实现方法,而不需要实现方法返回响应式类型(如 Mono
或 Flux
)。
请注意,根据方法的声明方式,协程上下文可能可用也可能不可用。为了保留对上下文的访问权限,可以使用 suspend
声明方法,或返回一个能够传递上下文的类型,例如 Flow
。
-
suspend fun findOne(id: String): User
: 通过挂起的方式同步获取一次数据。 -
fun findByFirstname(firstname: String): Flow<User>
: 获取数据流。Flow
会立即创建,而数据会在Flow
交互时(如Flow.collect(…)
)被获取。 -
fun getUser(): User
: 阻塞线程 并一次性地获取数据,且不会传播上下文。应避免使用这种方式。
只有在仓库扩展了 CoroutineCrudRepository
接口时,协程仓库才会被发现。