`kotlinx.coroutines.withContext` 与 Spring WebFlux 一起使用安全吗?
Is `kotlinx.coroutines.withContext` safe to use with Spring WebFlux?
假设我有一个 Spring 使用 Kotlin 实现的 WebFlux 控制器,看起来像这样:
@RestController
@RequestMapping("/api/foo")
class MyController {
@GetMapping
suspend fun getFoo(): FooResource {
return withContext(Dispatchers.IO) {
// fetch some resource with some expensive blocking IO call
}
}
}
据我了解 WebFlux 的并发模型,只有一个线程可用于处理请求,因此如果出于某种原因我无法避免阻塞 IO 调用,我需要以某种方式将其卸载到另一个线程。 kotlinx.coroutines.withContext
助手应该正是这样做的,IO
调度程序是专门为这种用例设计的。`我在几篇博客文章中看到过这种模式,所以它似乎是常识。
但是,[Dispatchers.IO
上的文档说:
This dispatcher shares threads with a Default dispatcher, so using withContext(Dispatchers.IO) { ... } does not lead to an actual switching to another thread — typically execution continues in the same thread. As a result of thread sharing, more than 64 (default parallelism) threads can be created (but not used) during operations over IO dispatcher.
所以这让我想知道:如果 WebFlux 只使用一个“主线程”来处理请求,即使我正在使用 withContext(Dispatchers.IO)
,阻塞 IO 仍然可能发生在这个线程中:这个模式安全吗使用,如果没有,我还应该做什么?
是的,它是安全的,您理解 withContext
正确。
您在此处提到的文档只是讨论了在 IO
和 Default
调度程序之间切换时对 Dispatchers.IO
的优化(避免了上下文切换)。
从 Default
/IO
线程池以外的其他线程使用 withContext(Dispatchers.IO)
将正确(并且总是)将上下文切换到该 IO 线程池,根据需要启动新线程来处理阻塞 IO,所以这应该是你的情况。
假设我有一个 Spring 使用 Kotlin 实现的 WebFlux 控制器,看起来像这样:
@RestController
@RequestMapping("/api/foo")
class MyController {
@GetMapping
suspend fun getFoo(): FooResource {
return withContext(Dispatchers.IO) {
// fetch some resource with some expensive blocking IO call
}
}
}
据我了解 WebFlux 的并发模型,只有一个线程可用于处理请求,因此如果出于某种原因我无法避免阻塞 IO 调用,我需要以某种方式将其卸载到另一个线程。 kotlinx.coroutines.withContext
助手应该正是这样做的,IO
调度程序是专门为这种用例设计的。`我在几篇博客文章中看到过这种模式,所以它似乎是常识。
但是,[Dispatchers.IO
上的文档说:
This dispatcher shares threads with a Default dispatcher, so using withContext(Dispatchers.IO) { ... } does not lead to an actual switching to another thread — typically execution continues in the same thread. As a result of thread sharing, more than 64 (default parallelism) threads can be created (but not used) during operations over IO dispatcher.
所以这让我想知道:如果 WebFlux 只使用一个“主线程”来处理请求,即使我正在使用 withContext(Dispatchers.IO)
,阻塞 IO 仍然可能发生在这个线程中:这个模式安全吗使用,如果没有,我还应该做什么?
是的,它是安全的,您理解 withContext
正确。
您在此处提到的文档只是讨论了在 IO
和 Default
调度程序之间切换时对 Dispatchers.IO
的优化(避免了上下文切换)。
从 Default
/IO
线程池以外的其他线程使用 withContext(Dispatchers.IO)
将正确(并且总是)将上下文切换到该 IO 线程池,根据需要启动新线程来处理阻塞 IO,所以这应该是你的情况。