|
此版本仍在开发中,尚未被视为稳定版本。如需最新稳定版本,请使用 Spring Data Cassandra 5.0.4! |
协程
依赖项
当类路径中包含 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 及以上。 |
响应式如何转换为协程?
对于返回值,从响应式(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是基于推送的,而Flux是推送-拉取混合模式 -
背压通过挂起函数实现
-
Flow仅有一个 挂起的collect方法,且操作符以 扩展函数 的形式实现 -
运算符易于实现,这要归功于协程(Coroutines)
-
扩展允许向
Flow添加自定义操作符 -
集合操作是挂起函数
-
map运算符 支持异步操作(无需flatMap),因为它接受一个挂起函数参数
阅读这篇关于使用 Spring、协程和 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 协程暴露数据访问的非阻塞特性。
协程仓库中的方法可以由查询方法或自定义实现提供支持。
调用自定义实现方法时,如果该自定义方法是 suspend 函数,则会将协程调用传播到实际的实现方法,而无需该实现方法返回诸如 Mono 或 Flux 等响应式类型。
请注意,根据方法声明的不同,协程上下文可能可用,也可能不可用。
为了保留对上下文的访问,请使用 suspend 声明您的方法,或者返回支持上下文传播的类型,例如 Flow。
-
suspend fun findOne(id: String): User:通过挂起的方式一次性同步获取数据。 -
fun findByFirstname(firstname: String): Flow<User>:检索一个数据流。Flow会被急切地创建,而数据则在与Flow交互时(例如调用Flow.collect(…))才被获取。 -
fun getUser(): User:一次性检索数据,阻塞线程且不传播上下文。 应避免使用此方式。
协程仓库仅在仓库接口继承了 CoroutineCrudRepository 接口时才会被发现。 |