跳到主要内容

协程

ChatGPT-4o-mini 中英对照 Coroutines

Kotlin 协程 是可挂起计算的实例,允许以命令式方式编写非阻塞代码。在语言层面,suspend 函数为异步操作提供了抽象,而在库层面,kotlinx.coroutines 提供了像 async { } 这样的函数和像 Flow 这样的类型。

Spring Data 模块在以下范围内提供对协程的支持:

依赖项

kotlinx-coroutines-corekotlinx-coroutines-reactivekotlinx-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>
xml
备注

支持的版本 1.3.0 及以上。

如何将 Reactive 转换为协程?

对于返回值,从 Reactive 到 Coroutines API 的转换如下:

  • fun handler(): Mono<Void> 变为 suspend fun handler()

  • fun handler(): Mono<T> 变为 suspend fun handler(): Tsuspend fun handler(): T?,具体取决于 Mono 是否可以为空(具有更强的静态类型优势)

  • fun handler(): Flux<T> 变为 fun handler(): Flow<T>

Flow 是协程世界中 Flux 的等价物,适用于热流或冷流,有限流或无限流,其主要区别如下:

  • Flow 是基于推送的,而 Flux 是推拉混合型

  • 反压通过挂起函数实现

  • Flow 只有一个 单一的挂起收集方法,操作符作为 扩展 实现

  • 操作符易于实现,这要归功于协程

  • 扩展允许向 Flow 添加自定义操作符

  • 收集操作是挂起函数

  • map 操作符 支持异步操作(无需 flatMap),因为它接受一个挂起函数参数

阅读这篇关于 使用 Spring、协程和 Kotlin Flow 进行响应式编程 的博客文章,了解更多细节,包括如何使用协程并发运行代码。

Repositories

这是一个协程仓库的示例:

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

协程仓库是建立在反应式仓库之上的,以通过 Kotlin 的协程暴露数据访问的非阻塞特性。协程仓库上的方法可以由查询方法或自定义实现支持。调用自定义实现方法会将协程调用传播到实际的实现方法,如果自定义方法是 suspend 可挂起的,则不需要实现方法返回反应式类型,例如 MonoFlux

请注意,根据方法声明,协程上下文可能会或可能不会可用。为了保留对上下文的访问,您可以使用 suspend 声明方法,或返回一种能够启用上下文传播的类型,例如 Flow

  • suspend fun findOne(id: String): User: 通过挂起一次性同步地检索数据。

  • fun findByFirstname(firstname: String): Flow<User>: 检索数据流。Flow 在数据通过 Flow 交互(Flow.collect(…))时被急切地创建。

  • fun getUser(): User: 一次性检索数据 阻塞线程 且不进行上下文传播。这应该避免。

备注

协程仓库仅在仓库扩展了 CoroutineCrudRepository 接口时才会被发现。