通过结构化并发和协程实现“即发即忘”

ste*_*eTV 4 kotlin kotlinx.coroutines

我有一个看起来像这样的小端点

\n\n
val numbers = it.bodyAsString.parseJsonList<Numbers>()\nprocessedNumbers = numberService.process(numbers)\nGlobalScope.launch {\n    sqsService.sendToSqs(processedNumbers)\n}\nit.response.setStatusCode(204).end()\n
Run Code Online (Sandbox Code Playgroud)\n\n

我使用 GlobalScope 的原因是因为生产者只需要在处理数字后进行确认,所以我试图在并行轨道中进行即发即忘的操作,以便能够立即响应生产者

\n\n

使用结构性货币执行此操作的 \xe2\x80\x9c 最佳实践\xe2\x80\x9d 方法是什么?我应该创建自己的作用域(例如 fireAndForgetScope 而不是 GlobalScope)吗?

\n

Ale*_*hin 5

正如您已经猜到的,在这种情况下创建自己的范围将是一个很好的解决方案。
您可以将其定义为控制器的成员:

private val bgScope = CoroutineScope(newFixedThreadPoolContext(4, "background-tasks"))
Run Code Online (Sandbox Code Playgroud)

那么用法与您正在做的非常相似:

val numbers = it.bodyAsString.parseJsonList<Numbers>()
processedNumbers = numberService.process(numbers)
bgScope.launch {
    sqsService.sendToSqs(processedNumbers)
}
it.response.setStatusCode(204).end()
Run Code Online (Sandbox Code Playgroud)

  • 请注意,“bgScope”现在有一个“Job”,可以在子进程失败时取消该“Job”,从而防止启动更多后台作业。为了避免这种情况,应该使用`SupervisorJob` (2认同)