小编Ser*_*tsa的帖子

来自阻塞代码的异步/等待 kotlin 协程

我使用的是 Spring boot,没有响应式 Web。

我尝试使用 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
    }
Run Code Online (Sandbox Code Playgroud)

但这段代码是按顺序运行的。

我该如何修复它?

spring async-await kotlin spring-boot kotlin-coroutines

4
推荐指数
1
解决办法
4276
查看次数