Created
February 9, 2018 11:40
-
-
Save jigewxy/418bdaf8d1f70e70cac4d886d467cf28 to your computer and use it in GitHub Desktop.
Use cluster for master/child process communication
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 app = require('express')(); | |
const bodyParser = require('body-parser'); | |
const cpus = 4; | |
var index = 0; | |
//next(); | |
if(cluster.isMaster) | |
{ | |
console.log(`Master ${process.id} is running`); | |
//Fork workers | |
for(let i=1; i<=cpus; i++) | |
{ | |
cluster.fork(); | |
} | |
/** create new worker after a worker is killed*/ | |
cluster.on('exit', (worker, code, signal)=>{ | |
console.log(`Worker ${worker.process.pid} died`); | |
console.log('creating new worker process'); | |
cluster.fork(); | |
}); | |
cluster.on('message', (worker, message) =>{ | |
console.log(`Received a message from ${worker.process.pid} : ${message}`); | |
}) | |
} else | |
{ | |
var pid = process.pid; | |
const jsonParser =bodyParser.json(); | |
app.get('/', (req, res)=>res.send(`worker process id is ${pid}`)); | |
app.get('/kill', (req,res)=>{ | |
res.send(`Now killing worker: ${pid}`); | |
process.exit(1); | |
}); | |
app.post('/send',jsonParser, (req, res)=>{ | |
var msg = JSON.stringify(req.body); | |
res.send(`send message ${msg} to master`); | |
process.send(msg); | |
} | |
); | |
app.listen(3000, () => console.log(`worker#${pid} now listening on port 3000`)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment