协程
依赖项
当 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 如何转换为协程?
对于返回值,从 Reactive 到协程 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方法,运算符作为 扩展 实现 -
运算符易于实现,这得益于协程
-
扩展允许向
Flow添加自定义运算符 -
收集操作是挂起函数
-
map运算符 支持异步操作(不需要flatMap),因为它接受一个挂起函数参数
阅读这篇关于 使用 Spring、协程和 Kotlin Flow 进行 Reactive 的博文,了解更多详细信息,包括如何使用协程并发运行代码。
存储库
这是一个协程存储库的示例。
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接口时,才会发现协程存储库。
|