Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save slaveofcode/046cef8a14ccc9868cae1ab09676b945 to your computer and use it in GitHub Desktop.
Save slaveofcode/046cef8a14ccc9868cae1ab09676b945 to your computer and use it in GitHub Desktop.
Express Example of master and workers killer
'use strict'
const cluster = require('cluster')
const os = require('os')
if (cluster.isMaster) {
let numOfWorkers = os.cpus().length
console.log(`Master cluster setting up ${numOfWorkers} workers..`)
for (let i=0; i < numOfWorkers; i++) {
cluster.fork()
}
// Master receiving message from worker
cluster.on('message', function(msg) {
console.log('message received: ' + JSON.stringify(msg))
if (cluster.workers[msg.workerId]) {
cluster.workers[msg.workerId].send({
command: 'kill',
workerId: msg.workerId
})
} else {
console.log('Worker already died...')
}
})
cluster.on('online', (worker) => {
console.log(`Worker ${worker.id} is online`)
})
cluster.on('exit', (worker, code, signal) => {
console.log(`Worker ${worker.id} died with code ${code}`)
console.log(`Starting a new worker`)
cluster.fork()
})
}
if (cluster.isWorker){
let app = require('express')()
// worker receiving message from master
process.on('message', (msg) => {
console.log(`worker ${cluster.worker.id} got message: ${JSON.stringify(msg)}`)
if (msg.command == 'kill' && msg.workerId == cluster.worker.id) {
console.log('-- killing this worker --')
process.exit(0)
}
})
app.all('/hello', (req, res) => {
res.send(`Hello from process id ${process.id}`)
})
app.all('/kill/:wid', (req, res) => {
try {
const wid = req.params.wid
// worker sending a message to master
process.send({command: 'shutdown', workerId: wid})
res.send('ok')
} catch(e) {console.log(e)}
})
let server = app.listen(1818, () => {
console.log(`Process ${process.pid} by worker id ${cluster.worker.id} is listening to all incoming requests`)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment