对于最新的稳定版本,请使用 Spring Data Commons 3.3.1! |
对于最新的稳定版本,请使用 Spring Data Commons 3.3.1! |
依赖
当 时,将启用协程支持,并且依赖项位于类路径中:kotlinx-coroutines-core
kotlinx-coroutines-reactive
kotlinx-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 |
反应式如何转化为协程?
对于返回值,从响应式 API 到协程 API 的转换如下:
-
fun handler(): Mono<Void>
成为suspend fun handler()
-
fun handler(): Mono<T>
变为或取决于是否可以为空(优点是更静态类型)suspend fun handler(): T
suspend fun handler(): T?
Mono
-
fun handler(): Flux<T>
成为fun handler(): Flow<T>
流
在协程世界中是等价的,适用于热流或冷流,有限流或无限流,主要区别如下:Flux
-
Flow
是基于推送的,而是基于推拉混合的Flux
-
背压通过悬挂功能实现
-
借助协程,运算符易于实现
-
扩展允许将自定义运算符添加到
Flow
-
收集操作正在暂停功能
-
Map
Operator 支持异步操作(不需要 ),因为它需要挂起函数参数flatMap
阅读这篇关于使用 Spring、协程和 Kotlin Flow 进行响应的博文,了解更多详细信息,包括如何与协程并发运行代码。
存储 库
下面是协程存储库的示例:
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 的协程公开数据访问的非阻塞特性。
协程存储库上的方法可以由查询方法或自定义实现提供支持。
如果自定义方法是 -able,则调用自定义实现方法会将协程调用传播到实际实现方法,而无需实现方法返回响应式类型,例如 或 。suspend
Mono
Flux
请注意,根据方法声明,协程上下文可能可用,也可能不可用。
若要保留对上下文的访问,请声明方法 using 或返回启用上下文传播的类型,例如 。suspend
Flow
-
suspend fun findOne(id: String): User
:通过挂起同步检索数据一次。 -
fun findByFirstname(firstname: String): Flow<User>
:检索数据流。 在交互时获取数据时急切地创建 ()。Flow
Flow
Flow.collect(…)
-
fun getUser(): User
:在阻塞线程且不进行上下文传播后检索数据。 应该避免这种情况。
协程存储库仅在存储库扩展接口时被发现。CoroutineCrudRepository |
协程存储库仅在存储库扩展接口时被发现。CoroutineCrudRepository |