当您使用 Cluster 之类的东西 fork 或启动多个 worker 时:
是否正在创建多个线程或 Node 进程实例?这是否打破了 Node 的单线程概念?
如何处理 worker 之间的请求? Cluster 是否提供某种智能机制来将所有请求负载均衡到多个 worker?
最佳答案
Cluster
使用 fork
,是的,它会自动平衡:
The worker processes are spawned using the
child_process.fork
method, so that they can communicate with the parent via IPC and pass server handles back and forth.[...]
When multiple processes are all
accept()
ing on the same underlying resource, the operating system load-balances across them very efficiently. There is no routing logic in Node.js, or in your program, and no shared state between the workers. Therefore, it is important to design your program such that it does not rely too heavily on in-memory data objects for things like sessions and login.
如果您将一个新的 node.js 实例算作另一个线程,您可能会认为这打破了 node.js 单线程概念,但是请记住,给定请求的所有回调都将在同一个 Node 中处理。 接受
原始请求的 js 实例。没有竞争条件,没有共享数据,只有相当安全的进程间通信。
参见 Cluster documentation获取更多信息。
关于node.js - Cluster 如何跟上 Node 的单线程概念?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15070169/