没有Webflux的Spring Kotlin Webapp需要同时执行两个任务才能以最佳方式产生结果
该应用程序不使用webflux和反应式编程,它使用一个普通的没有Webflux的Spring Kotlin Webapp需要同时执行两个任务才能以最佳方式产生结果,spring,kotlin,concurrency,async-await,spring-webclient,Spring,Kotlin,Concurrency,Async Await,Spring Webclient,该应用程序不使用webflux和反应式编程,它使用一个普通的crudepository连接到一个需要很长时间才能响应的数据库,并使用WebClient执行对其他服务的请求,但使用block()函数以同步方式获得结果。我想更改以下代码,以便两个调用同时发生: @Service class CustomerService( val profileClient: WebClient, val customerRepository: CustomerRepository ) {
crudepository
连接到一个需要很长时间才能响应的数据库,并使用WebClient
执行对其他服务的请求,但使用block()
函数以同步方式获得结果。我想更改以下代码,以便两个调用同时发生:
@Service class CustomerService(
val profileClient: WebClient,
val customerRepository: CustomerRepository
) {
fun getCustomer(id: String) : CustomerData {
val customer = customerRepository.findById(id)
val profile = profileClient.get().uri("/v1/profile/{id}", id)
.retrieve().bodyToMono<Profile>()
.block()
return CustomerData(customer, profile)
}
}
@服务类CustomerService(
val Profile客户端:网络客户端,
val customerRepository:customerRepository
) {
fun getCustomer(id:String):CustomerData{
val customer=customerRepository.findById(id)
val profile=profileClient.get().uri(“/v1/profile/{id}”,id)
.retrieve().bodyToMono()
.block()
返回客户数据(客户,配置文件)
}
}
如果调用customerRepository.findById(id)
需要20毫秒,而profileClient.get..
需要50毫秒,那么总共需要70毫秒,而如果我同时调用这两个调用,应该需要大约50毫秒
我无法使用Webflux将应用程序迁移到完全反应的版本,因为它需要迁移大量代码。如果需要并发性,可以使用 您的代码如下所示:
fun getCustomer(id: String) : CustomerData = runBlocking {
val customer = async { customerRepository.findById(id) }
val profile = async { profileClient.get().uri("/v1/profile/{id}", id)
.retrieve().bodyToMono<Profile>()
.block() }
CustomerData(customer.await(), profile.await())
}
fun getCustomer(id:String):CustomerData=runBlocking{
val customer=async{customerRepository.findById(id)}
val profile=async{profileClient.get().uri(“/v1/profile/{id}”,id)
.retrieve().bodyToMono()
.block()}
CustomerData(customer.await(),profile.await())
}
谢谢@Neo成功了!我还不能检查它是如何在高需求工作负载中扩展和执行的,runBlocking
不允许设置线程池,我还不能确定它是否使用了调用async{…}
块的同一线程,或者它使用了全局线程池,还有什么限制,在这种情况下,对于低负载,它会大幅减少响应时间,但在高负载情况下,它会关闭服务或使其变得更慢,只是想弄明白…@marianrouiz With coroutines您不需要关心线程池,只需要关心coroutinecontext。由于协同程序非常轻量级(而且我在我的生产环境中经常大量使用它们),我不能告诉您一个限制,因为我从未达到过任何限制。你可以自己尝试,阅读一些关于上下文和调度员的kotlin文档-他们可能非常强大-