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