Ktor REST 响应和异步代码执行

Ktor REST response and async code execution

问题: 我想解除对我的 KTOR 响应的代码部分的阻塞,这些代码需要更长的时间并且可以在事后以异步方式执行。

REST 响应的核心业务逻辑不应该等待发送电子邮件、kafka 事件等异步任务。

我尝试过的: 我通过此代码示例获得了预期的结果。我可以看到其余响应立即返回并且不等待延迟任务(电子邮件和 Kafka 消息)。

目前我不清楚是否需要将这些行保留在 runBlocking 代码中

val patient = PatientService.addPatient()
//Return REST response    
call.respond(patient)

问题 如果我将它排除在运行阻塞代码之外,整个其余响应将被阻塞,直到电子邮件和 kafka 事件代码完成。 这是卸载某些延迟代码执行的正确方法吗 来自 KTOR 中主要 REST API 响应的逻辑?

fun Route.patientRoute(){
    route("/patient") {
        post (""){
        runBlocking {

            val patient = PatientService.addPatient() //..Business logic to add a new patient


            launch { //unblock the REST response from certain async. tasks
                sendKafkaEvent()
                sendEmail()
            }


            call.respond(patient) //Return REST response    
            }
        }
    }
}

suspend fun sendEmail() {
    delay(5000L)    //Mock some delay in the operation
}

suspend fun sendKafkaMessage() {
    delay(5000L) //Mock some delay in the operation
}

我会首先 运行 异步任务,然后调用 PatientService.addPatient() 以传递其返回值给 call.respond。 此外,您可以为您的任务指定不同的 dispatcher

post("") {
    launch(Dispatchers.IO) {
        sendEmail()
    }

    launch(Dispatchers.IO) {
        sendKafkaEvent()
    }

    call.respond(PatientService.addPatient())
}