Issue
I'm use Spring boot without reactive Web.
I try to run some async request with Kotlin coroutines
@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
}
But this code runs sequentially.
How can I fix it?
Solution
That code is work in parallel:
@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 withContext(Dispatchers.IO) {
restTemplate.getForEntity("http://localhost:9090/world", World::class.java).body!!.payload
}
}
private suspend fun hello(restTemplate: RestTemplate): String {
logger.info("Getting HELLO")
return withContext(Dispatchers.IO) {
restTemplate.getForEntity("http://localhost:9090/hello", Hello::class.java).body!!.payload
}
}
Answered By - Sergey Nikulitsa
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.