|
此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Data Commons 3.3.4! |
|
此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Data Commons 3.3.4! |
依赖
当 和 dependencies 位于 classpath 中时,将启用协程支持: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>
支持的版本及更高版本。1.3.0 |
支持的版本及更高版本。1.3.0 |
Reactive 如何转换为 Coroutines?
对于返回值,从 Reactive API 到 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 在 Coroutines 世界中是等效的,适用于热流或冷流、有限流或无限流,主要区别如下:Flux
-
Flow是基于推拉的,而 是推拉混合的Flux -
背压通过挂起功能实现
-
Flow只有一个 suspendingcollect方法,并且运算符作为扩展实现 -
借助协程,运算符易于实现
-
扩展允许将自定义运算符添加到
Flow -
收集操作正在挂起函数
-
map运算符支持异步操作(不需要),因为它需要一个 suspending 函数参数flatMap
有关更多详细信息,包括如何与协程并发运行代码,请参阅这篇关于使用 Spring、Coroutines 和 Kotlin Flow 实现反应式的博文。
存储 库
以下是 Coroutines 存储库的示例:
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 存储库中的方法可以由查询方法或自定义实现提供支持。
如果自定义方法是 -able,则调用自定义实现方法会将协程调用传播到实际的实现方法,而无需实现方法返回反应式类型,例如 or 。suspendMonoFlux
请注意,根据方法声明,协程上下文可能可用,也可能不可用。
要保留对上下文的访问,请使用 USING 声明方法,或返回启用上下文传播的类型,例如 .suspendFlow
-
suspend fun findOne(id: String): User:一次检索数据,并通过暂停同步检索数据。 -
fun findByFirstname(firstname: String): Flow<User>:检索数据流。 在交互时获取数据时,会急切地创建 ()。FlowFlowFlow.collect(…) -
fun getUser(): User:在阻塞线程后检索数据,无需上下文传播。 应避免这种情况。
仅当存储库扩展接口时,才会发现协程存储库。CoroutineCrudRepository |
仅当存储库扩展接口时,才会发现协程存储库。CoroutineCrudRepository |