Kotlin Coroutines-无需等待即可在API呼叫和返回API呼叫中启动功能
我有一个API电话,我想开始长时间的运行工作,然后再返回200。目前,它将开始工作并继续前进,但是一旦初始功能完成了需要做的事情,它似乎仍然等到Coroutine完成。我敢肯定,这与我对Kotlin Coroutines相对较新的理解有关。
fun apiCall() {
log.info("started")
longJob()
log.info("finished")
return ResponseEntity.ok()
}
fun longJob() {
runBlocking{
launch {
do stufff...
}
}
}
因此,基本上,我希望看到日志打印,然后启动Longjob,然后在Postman中看到200。但是实际上,我已经打印出了两个日志,而且工作开始了,但是直到工作完成之前,我才看到我的200ok。
I have an api call that I want to kick off a long running job and then return a 200 ok. Currently it will kick of the job and move on, but once the initial function finishes what it needs to do, it still seems to wait until the coroutine has finished. I'm sure this is related to my relatively new understanding of kotlin coroutines.
fun apiCall() {
log.info("started")
longJob()
log.info("finished")
return ResponseEntity.ok()
}
fun longJob() {
runBlocking{
launch {
do stufff...
}
}
}
So basically I'm expected to see the logs print and then kick off the longJob and then see 200 in postman. But I'm actually getting both logs printed out as well as the job kicked off, but I don't see my 200ok until the job finishes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我正确理解,您想在后台启动
longjob
,然后返回200ok
状态,而无需等待longjob
完成。如果是这种情况,那么您不能在此处使用runblocking
,它会阻止当前线程,直到所有作业都在其中启动,完成。您可以创建一个coroutinescope
,然后启动并忘记长期运行的任务。示例代码:在此示例日志中,“启动”和“完成”将在
longjob()
开始执行之前打印。If I understand correctly, you want to launch the
longJob
in background, and return200ok
status without waiting forlongJob
to finish. If this is the case then you can't userunBlocking
here, it blocks the current thread until all jobs, launched in it, finish. You can create aCoroutineScope
and launch and forget a long running task. The sample code:In this sample logs "started" and "finished" will be printed before
longJob()
starts executing.