乐闻世界logo
搜索文章和话题

How to Implement Multi-Processing in Node.js and Process Communication

2024年6月24日 16:43

In Node.js, you can utilize the cluster module to spawn multiple processes, thereby effectively leveraging multi-core CPU resources. The cluster module creates a group of Node.js processes that share the same server port.

The following are the basic steps to use the cluster module:

  1. Import the cluster module and other required modules.
  2. Use cluster.isMaster to determine if the current process is the master process.
  3. In the master process, use cluster.fork() to spawn worker processes.
  4. In worker processes, execute actual application code, such as setting up an HTTP server.
  5. Listen for relevant events to handle worker process startup, online status, and exit events.

Process communication can be achieved as follows:

  • The master process sends messages to worker processes using worker.send().
  • Worker processes send messages to the master process using process.send().
  • Listen for the message event to receive messages.

Below is a simple example of creating multiple worker processes and implementing communication between the master and worker processes:

javascript
const cluster = require('cluster'); const http = require('http'); const numCPUs = require('os').cpus().length; if (cluster.isMaster) { console.log(`Master process ${process.pid} is running`); // Fork worker processes. for (let i = 0; i < numCPUs; i++) { const worker = cluster.fork(); // Master process receives messages from worker processes worker.on('message', (msg) => { console.log(`Master process received message '${msg}' from worker process ${worker.process.pid}`); }); } cluster.on('exit', (worker, code, signal) => { console.log(`Worker process ${worker.process.pid} has exited`); }); } else { // Worker processes can share any TCP connections. // In this example, it is an HTTP server. http.createServer((req, res) => { res.writeHead(200); res.end('Hello World\n'); // Worker process sends a message to the master process process.send(`Worker process ${process.pid} received a request`); }).listen(8000); console.log(`Worker process ${process.pid} has started`); }

In this example, the master process creates worker processes equal to the number of CPU cores and sets up a message listener. Whenever a worker process receives an HTTP request, it sends a message to the master process. The master process listens for these messages and outputs relevant information to the console.

This approach allows Node.js applications to run more efficiently on multi-core CPUs, and the message passing mechanism between master and worker processes enables them to exchange information.

标签:JavaScriptNodeJS