【发布时间】:2021-09-08 14:55:44
【问题描述】:
你好堆栈溢出! 我正在编写一个小型服务网络应用程序,它接受使用 Spring Boot kotlin 发送电子邮件的数据。我的问题是如何让控制器在收到请求后立即响应并在后台线程中发送实际的电子邮件。首先控制器发送电子邮件,然后在rabbitMQ上发布消息,然后才返回响应作为指定字符串。
@RestController
class MailController(private val emailService: EmailService, private val msgSender: CustomMessageSender) {
@PostMapping("/api/sendemail")
suspend fun sendEmail(@RequestBody request: Email): String {
coroutineScope {
launch(Dispatchers.IO) {
try {
emailService.sendMail(request.to, request.subject!!, request.msg)
delay(2000)
msgSender.sendMessage()
} catch (e: Exception) {
println(e)
}
}
}
return "email queued"
}
}
【问题讨论】:
-
这应该有效。尝试
async而不是launch -
@sidgate 不,它不应该与
coroutineScope一起使用,因为这个函数会等到子协程完成后再恢复
标签: spring-boot kotlin kotlin-coroutines coroutine