node.js - Cluster 如何跟上 Node 的单线程概念?

标签 node.js node-cluster

当您使用 Cluster 之类的东西 fork 或启动多个 worker 时:

  1. 是否正在创建多个线程或 Node 进程实例?这是否打破了 Node 的单线程概念?

  2. 如何处理 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/

相关文章:

css - 为什么 node-sass 生成的 CSS 文件不在第一个 GET 请求中加载?

javascript - Node.js 中的视频流

node.js - Node cluster.isPrimary 未定义

javascript - 如何保留共享 Node 集群中所有 Node 进程的变量?

javascript - Node.js 集群

javascript - NodeJS集群,真的需要吗?

javascript - 如何有条件地检查对象值是否已设置或等于 smth 并跟踪更改?

mysql - Node.js 与 knex + Mysql 重命名列时迁移错误导致默认值

javascript - 在 MongoDB 中使用异步/等待时,在应用游标方法之前获取文档总数?