【发布时间】:2020-12-13 03:16:44
【问题描述】:
我正在使用没有响应式 Web 的 Spring Boot。
我尝试使用 Kotlin 协程运行一些异步请求
@GetMapping
fun test(): Message {
val restTemplate = RestTemplate()
return runBlocking {
val hello = async { hello(restTemplate) }
val world = async { world(restTemplate) }
Message("${hello.await()} ${world.await()}!")
}
}
private suspend fun world(restTemplate: RestTemplate): String {
logger.info("Getting WORLD")
return restTemplate.getForEntity("http://localhost:9090/world", World::class.java).body!!.payload
}
private suspend fun hello(restTemplate: RestTemplate): String {
logger.info("Getting HELLO")
return restTemplate.getForEntity("http://localhost:9090/hello", Hello::class.java).body!!.payload
}
但是这段代码是按顺序运行的。
我该如何解决?
【问题讨论】:
-
restTemplate.getForEntity是挂起函数吗? -
没有。这不是暂停乐趣
-
仅仅将一个函数标记为挂起并不能使它成为可挂起或异步的,另一个副作用是
runBlocking是单线程的,所以单线程将首先启动然后被阻塞,然后只有第二个请求将发生。您必须使用withContext(Dispatchers.IO) { /* Blocking Call */ }包装阻塞调用。
标签: spring spring-boot kotlin async-await kotlin-coroutines