Last active
August 17, 2017 05:44
-
-
Save beeplove/3956f8a5eedee533f43463bd1ebe0e32 to your computer and use it in GitHub Desktop.
fork child process from master using node-cluster and let them re-spawn after a minimum interval but before a maximum interval
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const cluster = require('cluster'); | |
const http = require('http'); | |
const numCPUs = require('os').cpus().length; | |
const min = 5 * 1000; | |
const max = 10 * 1000; | |
const waitBeforeKill = 2 * 1000; | |
cluster.on("fork", (worker) => { | |
console.log("worker forked: ", worker.process.pid); | |
}); | |
cluster.on("online", (worker) => { | |
console.log("worker became online: ", worker.process.pid); | |
setTimeout(() => { | |
worker.disconnect(); | |
}, min + (Math.random() * (max - min))); | |
}); | |
cluster.on("disconnect", (worker) => { | |
console.log("worker disconnected: ", worker.proces.pid); | |
setTimeout(() => { | |
worker.kill(); | |
}, waitBeforeKill); | |
}); | |
cluster.on("exit", (worker, code, signal) => { | |
cluster.fork(); | |
}); | |
if (cluster.isMaster) { | |
console.log("cluster is a Master"); | |
for (let i = 0; i < numCPUs; i++) { | |
const worker = cluster.fork(); | |
} | |
} else { | |
console.log("cluster is a Worker"); | |
http.createServer((req, res) => { | |
setTimeout(() => { // Added delay to make the response time longer | |
res.writeHead(200); | |
res.end('hello world\n'); | |
}, 1000 * 1); | |
}).listen(8000); | |
console.log(`Worker ${process.pid} started`); | |
} | |
// ab -n100 -c5 http://localhost:8000/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment