aldikhan13

Multiple Thead Process Nodejs

Aug 29th, 2020 (edited)
381
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const app = require('./src/app')
  2. const http = require('http').createServer(app)
  3. const cluster = require('cluster')
  4. const coreThread = require('os').cpus()
  5.  
  6. /**
  7.  * @description this method for use many core cpu in my local machine, for increase
  8.  *  performance in Nodejs application, because Nodejs is running in single threads mode
  9.  */
  10.  
  11. // run cluster mode
  12. if (cluster.isMaster) {
  13.   // get core many cpu in my local machine
  14.   for (let i = 0; i < coreThread.length; i++) {
  15.     cluster.fork()
  16.   }
  17.  
  18.   // extract many cpu in local machine
  19.   const workersTread = []
  20.   for (const id in cluster.workers) {
  21.     workersTread.push(id)
  22.   }
  23.  
  24.   // send message to worker master if any worker died based on process id
  25.   workersTread.forEach(async (pid, _) => {
  26.     await cluster.workers[pid].send({
  27.       from: 'isMaster',
  28.       type: 'SIGKILL',
  29.       message: 'cleanup is worker dead and change to new worker'
  30.     })
  31.   })
  32.  
  33.   // notify worker active and worker dead
  34.   if (process.env.NODE_ENV !== 'production') {
  35.     cluster.on('online', (worker) => {
  36.       if (worker.isConnected()) {
  37.         console.log(`worker active pid: ${worker.process.pid}`)
  38.       }
  39.     })
  40.  
  41.     cluster.on('exit', (worker, code, signal) => {
  42.       if (worker.isDead()) {
  43.         console.log(`worker dead pid: ${worker.process.pid}`)
  44.       }
  45.       cluster.fork()
  46.     })
  47.  
  48.     cluster.on('message', (worker, { from, message }) => {
  49.       console.log(`From: ${from} - Worker: ${worker.process.pid} - Message: ${message}`)
  50.     })
  51.   }
  52. } else {
  53.   // if the worker dies, execute this process and create new worker
  54.   if (cluster.isWorker) {
  55.     process.on('message', (msg) => {
  56.       if (msg.from === 'isMaster' && msg.type === 'SIGKILL') {
  57.         process.send({
  58.           from: 'isWorker',
  59.           message: `yes my lord ${msg.from}`
  60.         })
  61.       }
  62.     })
  63.     process.on('exit', () => {
  64.       process.exit(process.exitCode)
  65.     })
  66.   }
  67.   // listening server port
  68.   http.listen(process.env.PORT, () => console.log(`server is running on ${process.env.PORT}`))
  69. }
Add Comment
Please, Sign In to add comment