协程
Kotlin 协程是可挂起计算的实例,允许以命令式方式编写非阻塞代码。在语言层面,suspend 函数为异步操作提供了一种抽象;而在库层面,kotlinx.coroutines 提供了诸如 async 之类的函数和 Flow 之类的类型。
Spring Data 模块在以下范围内提供对协程的支持:
依赖
当 classpath 中存在 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.7.0 及以上版本。
响应式如何转换为协程?
对于返回值,从响应式 API 到协程 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添加自定义操作符 -
collect 操作是挂起函数
-
map 操作符支持异步操作(无需
flatMap),因为它接受一个挂起函数参数
更多细节(包括如何使用协程并发运行代码),请阅读这篇关于使用 Spring、协程和 Kotlin Flow 走向响应式的博客文章。
仓库
以下是一个协程仓库的示例:
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:阻塞线程地检索一次数据,且不进行上下文传播。应避免这种方式。
协程仓库仅在仓库继承 CoroutineCrudRepository 接口时才会被发现。