协程

Kotlin 协程(Coroutines) 是可暂停计算的实例,允许以命令式方式编写非阻塞代码。从语言层面看,suspend 函数为异步操作提供了抽象;从库层面看,kotlinx.coroutines 提供了诸如 async { } 的函数以及 Flow 等类型。

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

依赖

当类路径中包含 kotlinx-coroutines-corekotlinx-coroutines-reactivekotlinx-coroutines-reactor 依赖时,将启用协程支持

在 Maven pom.xml 中添加的依赖
<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)?

对于返回值,从响应式 API 到协程 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 是基于推(push-based)的,而 Flux 是推拉混合(push-pull hybrid)的

  • 背压(Backpressure)通过 suspend 函数实现

  • Flow 只有一个 单一的 suspend collect 方法,运算符实现为扩展(extensions)

  • 借助协程,运算符易于实现

  • 扩展允许向 Flow 添加自定义运算符

  • 收集操作是 suspend 函数

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

阅读这篇关于使用 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 方法,调用自定义实现方法会将协程调用传播到实际的实现方法,而无需实现方法返回 MonoFlux 等响应式类型。

请注意,协程上下文是否可用取决于方法的声明。为了保留对上下文的访问,可以使用 suspend 声明方法,或者返回支持上下文传播的类型,例如 Flow

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

  • fun findByFirstname(firstname: String): Flow<User>: 检索数据流。Flow 会被立即创建,而数据则在与 Flow 交互(Flow.collect(…))时被获取。

  • fun getUser(): User: 一次性检索数据,**阻塞线程**,且没有上下文传播。应避免使用此方法。

只有当 Repository 扩展 CoroutineCrudRepository 接口时,才能发现协程 Repository。