协程

Kotlin 协程 是可挂起计算的实例,允许以命令式方式编写非阻塞代码。在语言层面,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 如何转换为协程?

对于返回值,从 Reactive 到协程 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 只有一个 单一的可挂起 collect 方法,并且操作符被实现为 扩展

  • 由于协程的存在,操作符易于实现

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

  • Collect 操作是可挂起函数

  • 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 的,调用自定义实现方法会将协程调用传播到实际的实现方法,而无需要求实现方法返回诸如 MonoFlux 的响应式类型。

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

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

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

  • fun getUser(): User:一次性检索数据,会阻塞线程,且没有上下文传播。应该避免这种情况。

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