协程
依赖
当 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 到协程 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 接口时,协程仓库才会被发现。 |