协程
依赖
当 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.3.0 及更高。 |
响应式如何转换为协程?
对于返回值,从响应式到协程 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
是基于推(push-based),而Flux
是推拉混合(push-pull hybrid) -
背压(Backpressure)通过挂起函数实现
-
Flow
只有一个 挂起collect
方法,并且操作符是作为 扩展 实现的 -
得益于协程,操作符易于实现
-
扩展允许为
Flow
添加自定义操作符 -
收集操作(Collect operations)是挂起函数
-
map
操作符 支持异步操作(无需flatMap
),因为它接受一个挂起函数参数
阅读这篇关于 使用 Spring、协程和 Kotlin Flow 实现响应式编程 的博客文章,了解更多详情,包括如何使用协程并发运行代码。
Repositories
这是一个协程 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>
}
协程 Repositories 构建于响应式 Repositories 之上,通过 Kotlin 协程暴露数据访问的非阻塞特性。协程 Repository 中的方法可以由查询方法或自定义实现支持。如果自定义方法是 suspend
-able 的,调用自定义实现方法会将协程调用传播到实际的实现方法,而无需实现方法返回响应式类型,例如 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 接口时,才能发现协程 Repositories。 |