协程
依赖
当 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是推拉混合的 -
背压通过可暂停函数实现
-
Flow只有一个 单一的可暂停collect方法,并且操作符作为 扩展 实现 -
借助协程,操作符易于实现
-
扩展允许向
Flow添加自定义操作符 -
收集操作是可暂停函数
-
map操作符 支持异步操作(无需flatMap),因为它接受一个可暂停函数参数
阅读这篇关于 使用 Spring、协程和 Kotlin Flow 进行响应式开发 的博客文章,了解更多详细信息,包括如何使用协程并行运行代码。
Repository
这是一个协程 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: 通过暂停一次性同步检索数据。 -
fun findByFirstname(firstname: String): Flow<User>: 检索数据流。Flow会立即创建,而数据在与Flow交互时(Flow.collect(…))获取。 -
fun getUser(): User: 一次性检索数据,阻塞线程且不传播上下文。应避免此做法。
仅当 Repository 扩展 CoroutineCrudRepository 接口时,才能发现协程 Repository。 |