我是 Kotlin/Coroutines 的新手,我注意到有两种不同的使用方式CoroutineScope
.
在任何函数中,选项 1 如下:
CoroutineScope(Dispatchers.Default).launch {
expensiveOperation()
}
选项 2 是通过实施CoroutineScope
类中的接口,覆盖CoroutineContext
,然后你可以轻松地启动协程launch
or async
:
@Service
class ServiceImpl() : CoroutineScope {
override val coroutineContext: CoroutineContext
get() = Dispatchers.Default + Job()
fun someFunction() {
launch {
expensiveOperation()
}
}
}
我目前正在开发一个后端端点,它将执行以下操作:
- 接受请求
- 将请求上下文保存到数据库
- 在后台启动一个非阻塞协程,对请求执行昂贵/冗长的操作,并立即返回 http 200。(本质上,一旦我们保存了上下文,我们就可以返回响应并让请求在后台处理)
这两个用例有什么区别,对于这种情况,获取CoroutineScope
?
该端点每秒可能会收到多个请求,而冗长的操作将需要一两分钟,因此肯定会同时处理多个请求,这些请求源自多个请求。
另外,如果是选项 2,我是否想将范围/上下文传递给进行繁重处理的函数?或者说这是没有必要的?例如:
类 ServiceImpl() : CoroutineScope {
override val coroutineContext: CoroutineContext
get() = Dispatchers.Default + Job()
fun someFunction() {
launch {
expensiveOperation(CoroutineScope(coroutineContext))
}
}
private fun expensiveOperation(scope: CoroutineScope)
{
// perform expensive operation
}
}
这是一个 Spring Boot 应用程序,我正在使用版本1.3
of Kotlin
.
如果您对如何最好地构建此服务类别有任何想法/建议,请告诉我。谢谢