Last active
July 26, 2021 14:09
-
-
Save drmalex07/d9ef1a2afe106ed8c7a7b459171d1773 to your computer and use it in GitHub Desktop.
An example multiprocessing (cluster) Node.js server application. #node.js #multiprocessing #express #cluster
This file contains hidden or 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
var cluster = require('cluster'); | |
var server = null; | |
var workers = null; | |
var info = null; | |
const TIMEOUT = 5; | |
const N = 2; | |
if (cluster.isMaster) { | |
// Master process | |
info = console.info.bind(undefined, '[master #' + process.pid + ']') | |
workers = new Array(N); | |
info('Spawning ' + N + ' workers...') | |
for (let i = 0; i < N; i++) { | |
workers[i] = cluster.fork(); | |
} | |
let numWorkers = N; | |
let shutdown = function () | |
{ | |
info('Shutting down workers...') | |
for (let worker of workers) { | |
// Send a message to workers so they can gracefully stop | |
worker.send('shutdown'); | |
worker.on('exit', function () { | |
if (--numWorkers == 0) { | |
info('All workers have finished. Exiting') | |
process.exit(0) | |
} | |
}) | |
} | |
}; | |
process.on('SIGTERM', shutdown); | |
process.on('SIGINT', shutdown); | |
} else { | |
// Worker process | |
info = console.info.bind(undefined, '[worker #' + process.pid + ']') | |
let app = require("./app") // an Express application | |
server = app.listen(3001, function () { | |
info('Started'); | |
}); | |
process.on('message', function (msg) { | |
switch (msg) { | |
case 'shutdown': | |
info('Received shutdown request from master: Closing connections...') | |
// Stop accepting connections, wait until existing connections close | |
server.close(function () { | |
info('Closed all connections.') | |
process.exit(0); | |
}); | |
setTimeout(function () { | |
info('Forcefully shutting down (some connections maybe still alive)') | |
process.exit(1); | |
}, TIMEOUT *1e+3) | |
break; | |
default: | |
break; | |
} | |
}); | |
// Ignore direct OS signals on workers; workers should only be | |
// controlled by the master process. | |
let ignore = function () { | |
info('Ignoring direct signal to worker...') | |
} | |
process.on('SIGTERM', ignore); | |
process.on('SIGINT', ignore); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment