Node.js cluster 浅尝

const cluster = require('cluster')
const http = require('http')
const numCPUs = require('os').cpus().length

const rssWarn = (50 * 1024 * 1024),
  heapWarn = (50 * 1024 * 1024)

const workers = {}

if (cluster.isMaster) {
  for (let i = 0; i < numCPUs; i++) {
    createWorker()
  }

  setInterval(() => {
    const time = Date.now()
    for (pid in workers) {
      if (workers.hasOwnProperty(pid) &&
        workers[pid].lastCb + 5000 < time) {
        console.log('Long runing worker ' + pid + ' killed')
        workers[pid].worker.kill()
        delete workers[pid]
        createWorker()
      }
    }
  }, 1000)
} else {
  http.Server((req, res) => {
    if (Math.floor(Math.random() * 200) === 4) {
      console.log(`Stopped ${process.pid} from ever finishing`)
      while (true) {
        continue
      }
    }
    res.writeHead(200)
    res.end(`hello world from ${process.pid}\n`)
  }).listen(8000)

  setInterval(function report() {
    process.send({
      cmd: 'reportMem',
      memory: process.memoryUsage(),
      process: process.pid
    })
  }, 1000)
}

function createWorker() {
  const worker = cluster.fork()
  const pid = worker.process.pid
  console.log(`Created worker: ${pid}`)

  workers[pid] = {
    worker: worker,
    lastCb: Date.now() - 1000
  }

  worker.on('message', m => {
    if (m.cmd === 'reportMem') {
      workers[m.process].lastCb = Date.now()

      if (m.memory.rss > rssWarn) {
        console.log(`Worker ${m.process} using too much memory.`)
      }
    }
  })
}