const cluster = require('cluster');
const http = require('http');
if (cluster.isPrimary) {
// Keep track of http requests
let numRequests = 0;
// Create two workers
const worker1 = cluster.fork();
const worker2 = cluster.fork();
// Count requests
function messageHandler(msg) {
if (msg.cmd && msg.cmd === 'notifyRequest') {
numRequests += 1;
console.log(`Total requests: ${numRequests}`);
}
}
// Listen for messages from workers
worker1.on('message', messageHandler);
worker2.on('message', messageHandler);
// Send periodic messages to workers
setInterval(() => {
// Send a message to both workers
worker1.send({ cmd: 'updateTime', time: Date.now() });
worker2.send({ cmd: 'updateTime', time: Date.now() });
}, 5000);
} else {
// Worker process
// Track the last update time
let lastUpdate = Date.now();
// Receive messages from the primary
process.on('message', (msg) => {
if (msg.cmd && msg.cmd === 'updateTime') {
lastUpdate = msg.time;
console.log(`Worker ${process.pid} received time update: ${new Date(lastUpdate)}`);
}
});
// Create an HTTP server
http.createServer((req, res) => {
// Notify the primary about the request
process.send({ cmd: 'notifyRequest' });
// Respond to the request
res.writeHead(200);
res.end(`Hello from Worker ${process.pid}. Last update: ${new Date(lastUpdate)}\n`);
}).listen(8000);
console.log(`Worker ${process.pid} started`);
}