Created
September 18, 2018 12:43
-
-
Save OrdinaryJellyfish/dec95dc593713c0733198dc5c03ce77a to your computer and use it in GitHub Desktop.
Simple Cluster example for Node.js
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 numCPUs = require('os').cpus().length | |
if (cluster.isMaster) { | |
console.log(`Master ${process.pid} is running`) | |
// Basic Multi-process Functionality | |
for (let i = 0; i < numCPUs; i++) { | |
cluster.fork() | |
} | |
cluster.on('online', worker => { | |
console.log(`Worker ${worker.process.pid} is online`) | |
}) | |
cluster.on('exit', (worker, code, signal) => { | |
console.log(`Worker ${worker.process.pid} died with code ${code} and signal ${signal}`) | |
console.log('Starting new worker') | |
cluster.fork() | |
}) | |
// Seamless Restarting | |
const workers = Object.values(cluster.workers) | |
const restartWorker = workerIndex => { | |
const worker = workers[workerIndex] | |
if (!worker) return | |
worker.on('exit', () => { | |
if (!worker.exitedAfterDisconnect) return | |
console.log(`Exited process ${worker.process.pid}`) | |
cluster.fork().on('listening', () => { | |
restartWorker(workerIndex + 1) | |
}) | |
}) | |
worker.disconnect() | |
} | |
process.on('SIGUSR2', () => { | |
console.log('SIGUSR2 signal received, restarting workers') | |
restartWorker(0) | |
}) | |
} else { | |
// Code here | |
console.log(`Worker ${process.pid} started`) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment