协程

Kotlin 协程是可挂起计算的实例,允许以命令方式编写非阻塞代码。 在语言方面,suspendfunctions 为异步作提供抽象,而在库端 kotlinx.coroutines 提供async { }和像Flow.spring-doc.cadn.net.cn

Spring Data 模块为以下范围内的协程提供支持:spring-doc.cadn.net.cn

依赖

在以下情况下启用协程支持kotlinx-coroutines-core,kotlinx-coroutines-reactivekotlinx-coroutines-reactordependencies 在 Classpath 中:spring-doc.cadn.net.cn

要在 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 API 到 Coroutines API 的转换如下:spring-doc.cadn.net.cn

  • fun handler(): Mono<Void>成为suspend fun handler()spring-doc.cadn.net.cn

  • fun handler(): Mono<T>成为suspend fun handler(): Tsuspend fun handler(): T?取决于Mono可以是空的,也可以是不空的(优点是更静态的类型)spring-doc.cadn.net.cn

  • fun handler(): Flux<T>成为fun handler(): Flow<T>spring-doc.cadn.net.cn

FlowFlux等效于协程世界,适用于热流或冷流、有限流或无限流,主要区别如下:spring-doc.cadn.net.cn

有关更多详细信息,包括如何与协程并发运行代码,请参阅这篇关于使用 Spring、Coroutines 和 Kotlin Flow 实现反应式的博文。spring-doc.cadn.net.cn

存储 库

以下是 Coroutines 存储库的示例:spring-doc.cadn.net.cn

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 的协程访问数据的非阻塞性质。 Coroutines 存储库中的方法可以由查询方法或自定义实现提供支持。 如果自定义方法为suspend-able 中,而不需要实现方法返回响应式类型,例如MonoFlux.spring-doc.cadn.net.cn

请注意,根据方法声明,协程上下文可能可用,也可能不可用。 要保留对上下文的访问,请使用suspend或返回启用上下文传播的类型,例如Flow.spring-doc.cadn.net.cn

  • suspend fun findOne(id: String): User:一次检索数据,并通过暂停同步检索数据。spring-doc.cadn.net.cn

  • fun findByFirstname(firstname: String): Flow<User>:检索数据流。 这Flow在获取数据时急切创建Flow交互 (Flow.collect(…)).spring-doc.cadn.net.cn

  • fun getUser(): User:在阻塞线程后检索数据,无需上下文传播。 应避免这种情况。spring-doc.cadn.net.cn

只有当存储库扩展CoroutineCrudRepository接口。