协程
依赖
当 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是基于推送的,而Flux是推拉混合的 -
背压通过 suspend 函数实现
-
Flow只有一个 单 suspendcollect方法,运算符作为 扩展 实现 -
得益于协程,运算符易于实现
-
扩展允许向
Flow添加自定义运算符 -
Collect 操作是 suspend 函数
-
map运算符 支持异步操作(无需使用flatMap),因为它接受一个 suspend 函数参数
阅读这篇关于 使用 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>
}
协程 Repository 基于反应式 Repository 构建,通过 Kotlin 的协程暴露数据访问的非阻塞特性。协程 Repository 上的方法可以由查询方法或自定义实现支持。如果自定义方法是可 suspend 的,调用自定义实现方法会将协程调用传播到实际的实现方法,而无需实现方法返回诸如 Mono 或 Flux 之类的反应式类型。
请注意,根据方法声明,协程上下文可能可用,也可能不可用。要保留对上下文的访问,可以使用 suspend 声明方法,或者返回一个允许上下文传播的类型,例如 Flow。
-
suspend fun findOne(id: String): User: 通过 suspending 一次性同步检索数据。 -
fun findByFirstname(firstname: String): Flow<User>: 检索数据流。Flow被立即创建,而数据则在Flow交互(Flow.collect(…))时获取。 -
fun getUser(): User: 一次性检索数据,阻塞线程且不进行上下文传播。应避免使用此方法。
只有当 Repository 继承 CoroutineCrudRepository 接口时,才能发现协程 Repository。 |