Skip to content

Instantly share code, notes, and snippets.

@chokri
Created September 1, 2020 08:56
Show Gist options
  • Save chokri/1944577092ca4e9773d85f5eb9ee8949 to your computer and use it in GitHub Desktop.
Save chokri/1944577092ca4e9773d85f5eb9ee8949 to your computer and use it in GitHub Desktop.
const cluster = require('cluster');
const http = require('http');
if (cluster.isMaster) {
// Keep track of http requests
let numReqs = 0;
setInterval(() => {
console.log(`numReqs = ${numReqs}`);
}, 1000);
// Count requests
function messageHandler(msg) {
if (msg.cmd && msg.cmd === 'notifyRequest') {
numReqs += 1;
}
}
// Start workers and listen for messages containing notifyRequest
const numCPUs = require('os').cpus().length;
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
for (const id in cluster.workers) {
cluster.workers[id].on('message', messageHandler);
}
} else {
// Worker processes have a http server.
http.Server((req, res) => {
res.writeHead(200);
res.end('hello world\n');
// Notify master about the request
process.send({ cmd: 'notifyRequest' });
}).listen(8000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment