Created
February 8, 2017 09:11
-
-
Save legend80s/aef2764d5a83361be9b9d88c9e230481 to your computer and use it in GitHub Desktop.
resilent fault-tolerant server with 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
/* eslint-disable no-console */ | |
/* eslint-disable no-param-reassign */ | |
const os = require('os'); | |
const graceful = require('graceful'); | |
const cluster = require('cluster'); | |
const app = require('../app'); | |
const isDev = process.env.NODE_ENV === 'development'; | |
if (cluster.isMaster) { | |
const workers = isDev ? 1 : os.cpus().length; | |
console.log(`Master cluster setting up ${workers} workers...`); | |
for (let i = 0; i < workers; i += 1) { | |
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 a new worker'); | |
cluster.fork(); | |
}); | |
process.on('exit', (code) => { | |
console.log(`cluster about to exit with code: ${code}`); | |
}); | |
process.on('uncaughtException', (err) => { | |
console.log(`Caught exception: ${err}`); | |
}); | |
} else if (cluster.isWorker) { | |
// 不要修改默认端口号 | |
// 6001 是集团服务器 Node.js 服务默认端口号 | |
const SERVER_NODEJS_PORT = 6001; | |
const LOCAL_PORT = 7001; | |
let port = isDev ? LOCAL_PORT : SERVER_NODEJS_PORT; | |
// 支持命令行传入 port: `npm run hot-server -- port=7001` | |
// console.log(`process.argv:`, process.argv); | |
// port=7001 | |
const matches = process.argv[2] && process.argv[2].match(/port=(\d{4})/); | |
if (matches) port = Number(matches[1]); | |
const server = app.listen(port, () => { | |
console.log(`Server listening on port ${server.address().port}`); | |
}); | |
graceful({ | |
server, | |
killTimeout: 30 * 1000, | |
error(err, throwErrorCount) { | |
if (err.message) { | |
err.message += ` (uncaughtException throw ${throwErrorCount} times on pid:${process.pid})`; | |
} | |
console.error(err); | |
}, | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment