Run express server using cluster setup (CC-54)

pull/45/head
HardiReady 2018-08-25 13:20:59 +02:00
parent d279556457
commit 8b0e2d91d3
1 changed files with 29 additions and 11 deletions

View File

@ -16,6 +16,12 @@ const cors = require('cors');
const mongoose = require('mongoose'); const mongoose = require('mongoose');
const {exec} = require('child_process'); const {exec} = require('child_process');
// cluster mode
const cluster = require('cluster');
const envWorkerNum = process.env.NODE_WORKER_COUNT;
const cpuCount = require('os').cpus().length;
const numWorkers = (envWorkerNum && envWorkerNum < cpuCount) ? envWorkerNum : cpuCount;
// own modules // own modules
const config = require('./config/config'); const config = require('./config/config');
const urls = require('./config/api-url'); const urls = require('./config/api-url');
@ -108,7 +114,7 @@ if (process.env.NODE_ENV === config.test.unit.env || process.env.NODE_ENV === co
const mongoServer = new MongodbMemoryServer(); const mongoServer = new MongodbMemoryServer();
mongoose.Promise = Promise; mongoose.Promise = Promise;
mongoServer.getConnectionString().then((mongoUri) => { mongoServer.getConnectionString().then((mongoUri) => {
mongoose.connect(mongoUri); mongoose.connect(mongoUri, { useNewUrlParser: true });
mongoose.connection.on('error', (e) => { mongoose.connection.on('error', (e) => {
if (e.message.code === 'ETIMEDOUT') { if (e.message.code === 'ETIMEDOUT') {
@ -139,17 +145,29 @@ if (process.env.NODE_ENV === config.test.unit.env || process.env.NODE_ENV === co
}); });
}); });
} else { } else {
const mongoosePromise = mongoose.connect(config.database.uri + config.database.db); mongoose.connect(config.database.uri + config.database.db, {useNewUrlParser: true}).then((db) => {
mongoosePromise.then((db) => { if (cluster.isMaster) {
app.listen(config.port, (err) => { // Fork workers
if (err !== undefined) { for (let i = 0; i < numWorkers; i++) {
error('Error on startup, ', err); cluster.fork();
} else {
logger('Listening on port ' + config.port);
signatureCronJob.start();
backupCronJob.start();
} }
}); logger(`Master ${process.pid} is running. Forking ${numWorkers} workers`);
//Check if worker id is died
cluster.on('exit', (worker, code, signal) => {
logger(`worker ${worker.process.pid} died`);
});
} else {
app.listen(config.port, (err) => {
if (err !== undefined) {
error(`Error on startup ${err}`);
} else {
logger(`Worker ${process.pid} started. Listening on port ${config.port}`);
signatureCronJob.start();
backupCronJob.start();
}
});
}
}); });
} }