首页 > 解决方案 > 结构化并发和协程的“一劳永逸”

问题描述

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

val numbers = it.bodyAsString.parseJsonList<Numbers>()
processedNumbers = numberService.process(numbers)
GlobalScope.launch {
    sqsService.sendToSqs(processedNumbers)
}
it.response.setStatusCode(204).end()

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

使用结构化货币进行此操作的“最佳实践”方式是什么?我应该创建自己的范围(例如 fireAndForgetScope 而不是 GlobalScope)吗?

标签: kotlinkotlinx.coroutines

解决方案


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

private val bgScope = CoroutineScope(newFixedThreadPoolContext(4, "background-tasks"))

然后用法与您正在执行的操作非常相似:

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

推荐阅读