How would you implement process communication when using cluster module in Node.js?
How would you implement process communication when using cluster module in Node.js?
To implement process communication when using the cluster module in Node.js, you can utilize the built-in Inter-Process Communication (IPC) capabilities that the cluster module provides. Here's a detailed explanation of how to achieve this:
The Node.js cluster module allows you to create child processes (workers), which can run simultaneously and communicate with the master process. This is particularly useful for taking advantage of multi-core systems to improve the performance of Node.js applications.
First, you need to include the cluster module in your Node.js application and check if the current process is the master process. If it is, you can fork worker processes; otherwise, you define the worker behavior:
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
// Fork workers.
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died`);
});
} else {
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.