协程
Kotlin 协程 是 Kotlin 的轻量级线程,允许以命令式方式编写非阻塞代码。在语言方面,挂起函数提供了异步操作的抽象,而在库方面,kotlinx.coroutines 提供了诸如 async { } 的函数和诸如 Flow 的类型。
Spring Framework 在以下范围提供协程支持
-
在 Spring MVC 和 WebFlux 的
@Controller注解中支持 Deferred 和 Flow 返回值 -
在 Spring MVC 和 WebFlux 的
@Controller注解中支持挂起函数 -
WebFlux.fn coRouter { } DSL
-
WebFlux
CoWebFilter -
在 RSocket
@MessageMapping注解方法中支持挂起函数和Flow -
RSocketRequester的扩展 -
Spring AOP
依赖项
当 kotlinx-coroutines-core 和 kotlinx-coroutines-reactor 依赖项在类路径中时,协程支持被启用
build.gradle.kts
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:${coroutinesVersion}")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactor:${coroutinesVersion}")
}
支持 1.4.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>
对于输入参数
-
如果不需要惰性,
fun handler(mono: Mono<T>)变为fun handler(value: T),因为可以调用挂起函数来获取值参数。 -
如果需要惰性,
fun handler(mono: Mono<T>)变为fun handler(supplier: suspend () → T)或fun handler(supplier: suspend () → T?)
Flow 是协程世界中的 Flux 等价物,适用于热或冷流,有限或无限流,主要区别如下
-
Flow是推式的,而Flux是推拉混合的 -
背压通过挂起函数实现
-
Flow只有一个 单个挂起collect方法,并且运算符作为 扩展 实现 -
得益于协程,运算符易于实现
-
扩展允许向
Flow添加自定义运算符 -
收集操作是挂起函数
-
map运算符 支持异步操作(无需flatMap),因为它接受一个挂起函数参数
阅读这篇关于 使用 Spring、协程和 Kotlin Flow 走向响应式 的博客文章,了解更多细节,包括如何使用协程并发运行代码。
控制器
这是一个协程 @RestController 的示例。
@RestController
class CoroutinesRestController(client: WebClient, banner: Banner) {
@GetMapping("/suspend")
suspend fun suspendingEndpoint(): Banner {
delay(10)
return banner
}
@GetMapping("/flow")
fun flowEndpoint() = flow {
delay(10)
emit(banner)
delay(10)
emit(banner)
}
@GetMapping("/deferred")
fun deferredEndpoint() = GlobalScope.async {
delay(10)
banner
}
@GetMapping("/sequential")
suspend fun sequential(): List<Banner> {
val banner1 = client
.get()
.uri("/suspend")
.accept(MediaType.APPLICATION_JSON)
.awaitExchange()
.awaitBody<Banner>()
val banner2 = client
.get()
.uri("/suspend")
.accept(MediaType.APPLICATION_JSON)
.awaitExchange()
.awaitBody<Banner>()
return listOf(banner1, banner2)
}
@GetMapping("/parallel")
suspend fun parallel(): List<Banner> = coroutineScope {
val deferredBanner1: Deferred<Banner> = async {
client
.get()
.uri("/suspend")
.accept(MediaType.APPLICATION_JSON)
.awaitExchange()
.awaitBody<Banner>()
}
val deferredBanner2: Deferred<Banner> = async {
client
.get()
.uri("/suspend")
.accept(MediaType.APPLICATION_JSON)
.awaitExchange()
.awaitBody<Banner>()
}
listOf(deferredBanner1.await(), deferredBanner2.await())
}
@GetMapping("/error")
suspend fun error() {
throw IllegalStateException()
}
@GetMapping("/cancel")
suspend fun cancel() {
throw CancellationException()
}
}
也支持使用 @Controller 进行视图渲染。
@Controller
class CoroutinesViewController(banner: Banner) {
@GetMapping("/")
suspend fun render(model: Model): String {
delay(10)
model["banner"] = banner
return "index"
}
}
WebFlux.fn
这是一个通过 coRouter { } DSL 定义的协程路由器及其相关处理程序的示例。
@Configuration
class RouterConfiguration {
@Bean
fun mainRouter(userHandler: UserHandler) = coRouter {
GET("/", userHandler::listView)
GET("/api/user", userHandler::listApi)
}
}
class UserHandler(builder: WebClient.Builder) {
private val client = builder.baseUrl("...").build()
suspend fun listView(request: ServerRequest): ServerResponse =
ServerResponse.ok().renderAndAwait("users", mapOf("users" to
client.get().uri("...").awaitExchange().awaitBody<User>()))
suspend fun listApi(request: ServerRequest): ServerResponse =
ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).bodyAndAwait(
client.get().uri("...").awaitExchange().awaitBody<User>())
}
事务
协程上的事务通过响应式事务管理以编程方式支持。
对于挂起函数,提供了 TransactionalOperator.executeAndAwait 扩展。
import org.springframework.transaction.reactive.executeAndAwait
class PersonRepository(private val operator: TransactionalOperator) {
suspend fun initDatabase() = operator.executeAndAwait {
insertPerson1()
insertPerson2()
}
private suspend fun insertPerson1() {
// INSERT SQL statement
}
private suspend fun insertPerson2() {
// INSERT SQL statement
}
}
对于 Kotlin Flow,提供了 Flow<T>.transactional 扩展。
import org.springframework.transaction.reactive.transactional
class PersonRepository(private val operator: TransactionalOperator) {
fun updatePeople() = findPeople().map(::updatePerson).transactional(operator)
private fun findPeople(): Flow<Person> {
// SELECT SQL statement
}
private suspend fun updatePerson(person: Person): Person {
// UPDATE SQL statement
}
}
上下文传播
Spring 应用程序 使用 Micrometer 进行可观测性支持。对于追踪支持,当前的观察结果通过 ThreadLocal 传播给阻塞代码,或者通过 Reactor Context 传播给响应式管道。但当前的观察结果也需要在挂起函数的执行上下文中可用。如果没有这一点,当前的“traceId”将不会自动添加到协程的日志语句中。
PropagationContextElement 运算符通常确保 Micrometer 上下文传播库 与 Kotlin 协程一起工作。
它需要 io.micrometer:context-propagation 依赖项,以及可选的 org.jetbrains.kotlinx:kotlinx-coroutines-reactor。通过调用 Hooks.enableAutomaticContextPropagation() 可以启用 CoroutinesUtils#invokeSuspendingFunction(Spring 用于将协程适配到 Reactor Flux 或 Mono)的自动上下文传播。
应用程序也可以显式使用 PropagationContextElement 来使用上下文传播机制增强 CoroutineContext
fun main() {
runBlocking(Dispatchers.IO + PropagationContextElement()) {
waitAndLog()
}
}
suspend fun waitAndLog() {
delay(10)
logger.info("Suspending function with traceId")
}
在这里,假设 Micrometer Tracing 已配置,生成的日志语句将显示当前的“traceId”,并为您的应用程序解锁更好的可观测性。