协程
依赖
在以下情况下启用协程支持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 到协程 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 进行响应式的博文,了解更多详细信息,包括如何与协程同时运行代码。
存储 库
以下是协程存储库的示例:
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-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接口。 |