Created
July 12, 2020 19:00
-
-
Save Alexzanderk/2452dcce5cf481c0563412e4b2bb0964 to your computer and use it in GitHub Desktop.
typescript cluster NodeJs
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
| import cluster from "cluster"; | |
| import { cpus } from "os"; | |
| const NUM_WORKERS = cpus().length; | |
| const PATH_TO_SERVER_APP = __dirname + '/app.ts'; | |
| cluster.setupMaster({ | |
| execArgv: ['-r', 'tsconfig-paths/register', '-r', 'ts-node/register'], | |
| exec: PATH_TO_SERVER_APP | |
| } as cluster.ClusterSettings) | |
| var workers: { [key: string]: cluster.Worker } = {}; | |
| const closeCluster = () => { | |
| console.log('Master stopped'); | |
| for (let pid in workers) { | |
| workers[pid].destroy('SIGTERM'); | |
| } | |
| process.exit(0); | |
| } | |
| console.info('Cluster: Master cluster setting up ' + NUM_WORKERS + ' workers...'); | |
| for (var i = 0; i < NUM_WORKERS; i++) { | |
| let worker = cluster.fork(); | |
| workers[worker.process.pid] = worker; | |
| } | |
| cluster.on('online', function (worker) { | |
| console.log('Cluster: Worker ' + worker.process.pid + ' is online'); | |
| }); | |
| cluster.on('exit', function (worker, code, signal) { | |
| console.log('Cluster: Worker ' + worker.process.pid + ' died with code: ' + code + ', and signal: ' + signal); | |
| console.log('Cluster: Starting a new worker'); | |
| let newWorker = cluster.fork(); | |
| workers[newWorker.process.pid] = newWorker; | |
| }); | |
| // Master can be terminated by either SIGTERM | |
| // or SIGINT. The later is used by CTRL+C on console. | |
| //Note for nodemon. Use nodemon --signal SIGTERM | |
| process.on('SIGTERM', closeCluster); | |
| process.on('SIGINT', closeCluster); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment