Это моя точка входа на сервер:
const numCPUs: number = require('os').cpus().length;
const PORT = process.env.PORT;
import server from './app';
import logger from './logger';
import Domain = require('domain');
import cluster = require('cluster');
if (cluster.isMaster) {
logger.info(`Master ${process.pid} is running`);
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
logger.info(`Worker ${worker.process.pid} died`);
cluster.fork();
});
} else {
const domain = Domain.create();
domain.on('error', (error) => {
logger.error(`Domain error in precess id:${ process.pid }`, error);
...
});
domain.run(() => {
server.listen(PORT, () => {
logger.info(`Express server id:${ process.pid } listening on port ${ PORT }`);
});
});
}
Я сделал html-страницу тестирования, которая отправляет запрос на тестирование 20 раз (или столько, сколько вам нужно) какому-либо обработчику.Это код:
app.route('/api/admin/getProjectFilters')
.get( async (req: Request, res: Response) => {
try {
const filters: projectFiltersType = {...};
// some actions
logger.info(`project filters were sent to admin in precess id:${ process.pid }`);
res.status(200).send(filters);
} catch (error) {
logger.error(`project filters sending to admin failed in precess id:${ process.pid }`, error);
res.status(500).send(error);
}
}
);
Запуск моего сервера и поиск в консоли:
2018-10-10T08:04:50.754Z [info]: Master 9584 is running
2018-10-10T08:04:52.273Z [info]: Express server id:11592 listening on port 2222
2018-10-10T08:04:52.334Z [info]: Express server id:2828 listening on port 2222
2018-10-10T08:04:52.352Z [info]: Express server id:2580 listening on port 2222
2018-10-10T08:04:52.383Z [info]: Express server id:4540 listening on port 2222
2018-10-10T08:04:58.330Z [info]: project filters were sent to admin in precess id:4540
2018-10-10T08:04:58.377Z [info]: project filters were sent to admin in precess id:4540
2018-10-10T08:04:58.447Z [info]: project filters were sent to admin in precess id:4540
2018-10-10T08:04:58.491Z [info]: project filters were sent to admin in precess id:4540
2018-10-10T08:04:58.538Z [info]: project filters were sent to admin in precess id:4540
Как видите, у меня есть несколько рабочих, но только один обрабатывает запросы клиентов.
Как заставить node.js использовать всех работников?