协程

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

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

依赖

当 classpath 中包含 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)?

对于返回值,从响应式 (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 是推拉混合模式

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

  • Flow 只有一个 挂起方法 collect,操作符则实现为扩展函数

  • 得益于协程,操作符易于实现

  • 扩展函数允许为 Flow 添加自定义操作符

  • collect 操作是挂起函数

  • 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>
}

协程 Repository 是基于响应式 Repository 构建的,通过 Kotlin 协程暴露数据访问的非阻塞特性。协程 Repository 中的方法可以由查询方法或自定义实现支持。如果自定义方法是可 suspend 的,调用自定义实现方法会将协程调用传播到实际的实现方法,而无需实现方法返回响应式类型,如 MonoFlux

请注意,根据方法的声明方式,协程上下文可能可用或不可用。要保留对上下文的访问,请使用 suspend 声明方法,或返回支持上下文传播的类型,例如 Flow

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

  • fun findByFirstname(firstname: String): Flow<User>: 检索数据流。Flow 在交互(Flow.collect(…))时急切地创建,并在需要时获取数据。

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

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