协程
Kotlin 协程 (Coroutines) 是可挂起计算的实例,允许以命令式方式编写非阻塞代码。在语言层面,suspend
函数为异步操作提供了抽象,而在库层面,kotlinx.coroutines 提供了诸如 async { }
等函数以及诸如 Flow
等类型。
Spring Data 模块在以下范围内提供对 Coroutines 的支持
依赖项
当 classpath 中包含 kotlinx-coroutines-core
、kotlinx-coroutines-reactive
和 kotlinx-coroutines-reactor
依赖项时,将启用 Coroutines 支持
<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?
对于返回值,从 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>
在 Coroutines 世界中,Flow
等同于 Flux
,适用于热流或冷流,有限流或无限流,主要区别如下
-
Flow
是推(push)模式,而Flux
是推拉(push-pull)混合模式 -
背压通过挂起函数实现
-
Flow
只有一个 挂起方法collect
,并且操作符实现为 扩展函数 -
借助于 Coroutines,操作符易于实现
-
扩展函数允许向
Flow
添加自定义操作符 -
Collect 操作是挂起函数
-
map
操作符 支持异步操作(无需flatMap
),因为它接受一个挂起函数参数
阅读这篇关于 使用 Spring、Coroutines 和 Kotlin Flow 实现响应式编程 的博客文章,了解更多详细信息,包括如何使用 Coroutines 并发运行代码。
存储库 (Repositories)
这里是一个 Coroutines repository 的示例
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 repository 构建在响应式 repository 之上,通过 Kotlin 的 Coroutines 暴露出数据访问的非阻塞特性。Coroutines repository 中的方法可以由查询方法或自定义实现支持。如果自定义方法是可 suspend
的,那么调用自定义实现方法会将 Coroutines 调用传播到实际实现方法,而无需实现方法返回像 Mono
或 Flux
这样的响应式类型。
请注意,根据方法声明的不同,协程上下文可能可用,也可能不可用。要保留对上下文的访问,请使用 suspend
声明方法,或返回一个支持上下文传播的类型,例如 Flow
。
-
suspend fun findOne(id: String): User
: 通过挂起一次性同步检索数据。 -
fun findByFirstname(firstname: String): Flow<User>
: 检索数据流。Flow
会被急切地创建,而数据则在与Flow
交互(Flow.collect(…)
)时才被获取。 -
fun getUser(): User
: 一次性检索数据,阻塞线程且不传播上下文。应避免这样做。
只有当 repository 扩展 CoroutineCrudRepository 接口时,才会发现 Coroutines repository。 |