How would you implement process communica...
How would you implement process communica...
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[1][2][3][4][5][6][11].
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 {
// Workers can share any TCP connection
// In this case, it is an HTTP server
http.createServer((req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(8000);
console.log(`Worker ${process.pid} started`);
}
IPC in the cluster module is automatically set up when you fork a new worker. Workers can communicate with the master process using process.send()
and the master can listen to these messages with the worker.on('message')
event:
if (cluster.isMaster) {
for (const id in cluster.workers) {
cluster.workers[id].on('message', (msg) => {
console.log(`Message from worker ${id}: ${msg}`);
});
}
} else {
process.send('Hello Master!');
}
You can customize the messages sent between the master and workers to handle specific tas...
expert
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào