search
HomeWeb Front-endJS TutorialHow to use cluster cluster in node

This time I will show you how to use the cluster cluster in node, and what are the precautions for using the cluster cluster in node. The following is a practical case, let's take a look.

Conclusion

Although the number of worker processes is usually set to the number of CPU processes, this number can be exceeded, and the main process is not created first.

if (cluster.isMaster) {
 // 循环 fork 任务 CPU i5-7300HQ 四核四进程
 for (let i = 0; i In the main process, cluster represents the main process (used for monitoring and sending events), process is its own process, and worker represents the child process, which is obtained through cluster.workers<p style="text-align: left;"></p>In the child process process represents a child process (used for listening and sending events), or the current child process can be represented through cluster.worker<p style="text-align: left;"></p>cluster.worker.process is equivalent to process (in a child process)<p style="text-align: left;"></p> <p style="text-align: left;"><span style="color: #ff0000">Main process and child processes communicate with each other<strong></strong></span></p><p style="text-align: left;"><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/061/021/7bf610320e74dbfb92ff934022d0032d-0.png?x-oss-process=image/resize,p_40" class="lazy" alt=""></p><ol class=" list-paddingleft-2">##cluster is used to monitor process(child) child process triggers Various events<li><p   style="max-width:90%"></p></li>#worker obtains in the main process and is used to communicate with itself. When the child process triggers an event, the current worker and related information will be returned to the corresponding event of the main process <li><p style="text-align: left;"></p></li>process(parent) The process instance of the main process itself, during the communication process The instance of the process(child) child process itself is basically not used. You can only obtain events for monitoring itself in the child process. <li><p style="text-align: left;"></p></li> It can be seen that the main process and the child process communicate with each other through such a triangular relationship, in which cluster and worker are obtained in the main process, and process(child) is the child process. The cluster notifies the child process by operating the worker, and the child process itself communicates with the cluster. Why is it designed this way? Because there will be multiple child processes, you can only choose which process to communicate with through the worker<li><p style="text-align: left;"></p></li>Scheduling policy for child processes cluster.schedulingPolicy</ol><p style="text-align: left;"></p><p style="text-align: left;">Scheduling Strategies, including cluster.SCHED_RR for cycle counting, and cluster.SCHED_NONE depending on the operating system. This is a global setting that will take effect immediately when the first worker process is spawned or cluster.setupMaster() is called. SCHED_RR is the default setting in all operating systems except Windows. Windows systems will also change to SCHED_RR as long as libuv can efficiently distribute IOCP handles without causing serious performance hits. cluster.schedulingPolicy can be implemented by setting the NODE_CLUSTER_SCHED_POLICY environment <span style="color: #ff0000"> variable <strong>. Valid values ​​for this environment variable include "rr" and "none". </strong></span>RR is Round-Robin polling scheduling, that is, each child process has an equal chance of obtaining events, which is the default except for windows. The scheduling strategy under windows is very strange, as shown in the figure below. Currently, there is no relevant API to set the scheduling strategy algorithm. node only provides us with two values</p><p style="text-align: left;"><a href="//m.sbmmt.com/wiki/70.html" target="_blank"></a></p>Process scheduling algorithm.png<p style="text-align: left;"></p>The test data is 1000 concurrent requests, repeated test 20 times, performance under windows. It can be seen that the scheduling algorithm of windows is chaotic. If it is the RR algorithm, the scheduling of the four processes should be on the same horizontal line. We have not set up a local Linux environment for the time being. Students who have the conditions can help test it. <p style="text-align: left;">Cluster's scheduling algorithm is currently related to the system's <img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/061/021/7bf610320e74dbfb92ff934022d0032d-1.png?x-oss-process=image/resize,p_40" class="lazy" alt=""></p><p   style="max-width:90%"></p>authentication issues between multiple processes<p style="text-align: left;"><br></p><p style="text-align: left;">Note: <span style="color: #ff0000">Node.js <strong>Routing logic is not supported. Therefore, when designing applications, you should not rely too much on memory data </strong> objects </span> (such as </p>session<p style="text-align: left;">s and logins, etc.). Because each worker process is an independent process, they can be shut down or regenerated at any time as needed without affecting the normal operation of other processes. As long as there are worker processes alive, the server can continue to handle connections. If there are no surviving worker processes, existing connections are lost and new connections are rejected. Node.js does not automatically manage the number of worker processes, but the specific application should manage the process pool according to actual needs. <a href="//m.sbmmt.com/wiki/1498.html" target="_blank"><p style="text-align: left;">文档中已明确说明了,每一个工作进程都是独立的,并且互相之间除了能够进行通信外,没有办法共享内存。所以在设计鉴权的时候,有两种方法</p>
<ol class=" list-paddingleft-2">
<li><p style="text-align: left;">通过共有的主进程存储鉴权信息,每次前端提交帐号密码,授权完成后,将 token 发送给主进程,下次前台<a href="//m.sbmmt.com/php/php-tp-demand.html" target="_blank">查询</a>时先在主进程获取授权信息</p></li>
<li><p style="text-align: left;">通过统一的外部 redis 存取</p></li>
</ol>
<p style="text-align: left;">两种方法看来还是第二种好的不要太多,因此多进程的环境下,应该使用外部数据库统一存储 token 信息</p>
<p style="text-align: left;"><span style="color: #ff0000"><strong>进一步的子进程间通信思考</strong></span></p>
<p style="text-align: left;">虽然 node 中并没有直接提供的进程间通讯功能,但是我们可以通过主进程相互协调进程间的通讯功能,需要定义标准的通信格式,例如</p>
<pre class="brush:php;toolbar:false">interface cmd {
 type: string
 from: number
 to: number
 msg: any
}

这样通过统一的格式,主进程就可以识别来自各个进程间的通信,起到进程通信中枢的功能

egg.js 中 agent 的实现

        +--------+     +-------+
        | Master || Agent |
        +--------+     +-------+
        ^  ^  ^
        /  |   \
       /   |    \
      /    |     \
     v     v     v
+----------+  +----------+  +----------+
| Worker 1 |  | Worker 2 |  | Worker 3 |
+----------+  +----------+  +----------+

我们看到 egg 在多进程模型之间实现了一个 agent 进程,这个进程主要负责对整个系统的定期维护

说到这里,Node.js 多进程方案貌似已经成型,这也是我们早期线上使用的方案。但后来我们发现有些工作其实不需要每个 Worker 都去做,如果都做,一来是浪费资源,更重要的是可能会导致多进程间资源访问冲突。举个例子:生产环境的日志文件我们一般会按照日期进行归档,在单进程模型下这再简单不过了:

每天凌晨 0 点,将当前日志文件按照日期进行重命名

销毁以前的文件句柄,并创建新的日志文件继续写入

试想如果现在是 4 个进程来做同样的事情,是不是就乱套了。所以,对于这一类后台运行的逻辑,我们希望将它们放到一个单独的进程上去执行,这个进程就叫 Agent Worker,简称 Agent。Agent 好比是 Master 给其他 Worker 请的一个『秘书』,它不对外提供服务,只给 App Worker 打工,专门处理一些公共事务。

这样我们可以指定一个进程作为 agent 进程,用于实现自己定义的事务。在 egg 中,主线程启动后 首先 fork agent进程,当 agent 进程启动完成后再启动具体的 worker 进程。参照上面的代码,相信这部分逻辑现在也不难实现了。这样 agent 就会获得 id 为1的进程

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

如何使用vue中实现点击空白处隐藏div实现

怎样使用JS+setInterval实现计时器

The above is the detailed content of How to use cluster cluster in node. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment