协程
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 如何转换为协程?
对于返回值,从 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
添加自定义操作符 -
Collect 操作是挂起函数
-
map 操作符支持异步操作(不需要
flatMap
),因为它接受一个挂起函数作为参数
阅读这篇关于 使用 Spring、协程和 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>
}
协程仓库建立在响应式仓库之上,通过 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
接口时才会被发现。