kotlin - 结构化并发和协程的“一劳永逸”
问题描述
我有一个看起来像这样的小端点
val numbers = it.bodyAsString.parseJsonList<Numbers>()
processedNumbers = numberService.process(numbers)
GlobalScope.launch {
sqsService.sendToSqs(processedNumbers)
}
it.response.setStatusCode(204).end()
我使用 GlobalScope 的原因是因为生产者只需要在处理完数字后才需要确认,所以我试图在并行轨道中进行火灾并忘记以便能够立即响应生产者
使用结构化货币进行此操作的“最佳实践”方式是什么?我应该创建自己的范围(例如 fireAndForgetScope 而不是 GlobalScope)吗?
解决方案
正如您已经猜到的那样,在这种情况下,创建自己的范围将是一个很好的解决方案。
您可以将其定义为控制器的成员:
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()
推荐阅读
- javascript - JS:通过 .push() 方法意外继承
- arduino - Arduino FastLed 随机行为
- stan - 如何在 Stan 模型中传递具有不同长度的向量列表和具有不同维度的矩阵列表?
- vb.net - 在这种情况下如何避免后期绑定?
- amazon-web-services - Terraform - 无法使用 t2.micro 实例类型安装“aws linux ami”
- java - 为 Prometheus 公开指标端点的替代方法是什么?
- typescript - tsconfig 在严格模式下出现问题并且类型 (...) 不可分配给类型 (...)
- swift - 如何从数据选择器中设置选定的时间,然后根据用户选择的时间显示包含时间输出的表格?
- google-cloud-storage - 如何使用带有签名网址的 gcs-resumable-upload
- python - 无法测量列表中每个项目的频率