协程
依赖
当 classpath 中包含 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 及以上。 |
响应式如何转换为协程?
对于返回值,从响应式到协程 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
添加自定义运算符 -
Collect 操作是可挂起函数
-
map
运算符 支持异步操作(无需flatMap
),因为它接受一个可挂起函数参数
阅读这篇关于 使用 Spring、协程和 Kotlin Flow 进行响应式编程 的博文以获取更多详细信息,包括如何使用协程并发运行代码。
Repository
这是一个协程 repository 的示例
interface CoroutineRepository : CoroutineCrudRepository<User, String> {
suspend fun findOne(id: String): User
fun findByFirstname(firstname: String): Flow<User>
suspend fun findAllByFirstname(id: String): List<User>
}
协程 repository 构建在响应式 repository 之上,通过 Kotlin 的协程暴露数据访问的非阻塞特性。协程 repository 中的方法可以由查询方法或自定义实现提供支持。如果自定义方法是可 suspend
的,调用自定义实现方法会将协程调用传播到实际的实现方法,而无需实现方法返回 Mono
或 Flux
等响应式类型。
请注意,根据方法声明的不同,协程上下文可能可用或不可用。为了保留对上下文的访问,请使用 suspend
声明您的方法,或返回一个能够传播上下文的类型,例如 Flow
。
-
suspend fun findOne(id: String): User
: 通过挂起一次性同步检索数据。 -
fun findByFirstname(firstname: String): Flow<User>
: 检索数据流。Flow
会急切地创建,而数据会在Flow
交互(Flow.collect(…)
)时获取。 -
fun getUser(): User
: 一次性检索数据,阻塞线程且不传播上下文。应避免这样做。
只有当 repository 扩展 CoroutineCrudRepository 接口时,才会发现协程 repository。 |