Multi-process across all CPU cores
This commit is contained in:
@@ -1,23 +1,41 @@
|
|||||||
const express = require('express');
|
const express = require('express');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
|
const cluster = require('cluster');
|
||||||
|
const numCPUs = require('os').cpus().length;
|
||||||
|
|
||||||
const app = express();
|
|
||||||
const PORT = process.env.PORT || 5000;
|
const PORT = process.env.PORT || 5000;
|
||||||
|
|
||||||
// Priority serve any static files.
|
// Multi-process to utilize all CPU cores.
|
||||||
app.use(express.static(path.resolve(__dirname, '../react-ui/build')));
|
if (cluster.isMaster) {
|
||||||
|
console.error(`Node cluster master ${process.pid} is running`);
|
||||||
|
|
||||||
// Answer API requests.
|
// Fork workers.
|
||||||
app.get('/api', function (req, res) {
|
for (let i = 0; i < numCPUs; i++) {
|
||||||
|
cluster.fork();
|
||||||
|
}
|
||||||
|
|
||||||
|
cluster.on('exit', (worker, code, signal) => {
|
||||||
|
console.error(`Node cluster worker ${worker.process.pid} exited: code ${code}, signal ${signal}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
} else {
|
||||||
|
const app = express();
|
||||||
|
|
||||||
|
// Priority serve any static files.
|
||||||
|
app.use(express.static(path.resolve(__dirname, '../react-ui/build')));
|
||||||
|
|
||||||
|
// Answer API requests.
|
||||||
|
app.get('/api', function (req, res) {
|
||||||
res.set('Content-Type', 'application/json');
|
res.set('Content-Type', 'application/json');
|
||||||
res.send('{"message":"Hello from the custom server!"}');
|
res.send('{"message":"Hello from the custom server!"}');
|
||||||
});
|
});
|
||||||
|
|
||||||
// All remaining requests return the React app, so it can handle routing.
|
// All remaining requests return the React app, so it can handle routing.
|
||||||
app.get('*', function(request, response) {
|
app.get('*', function(request, response) {
|
||||||
response.sendFile(path.resolve(__dirname, '../react-ui/build', 'index.html'));
|
response.sendFile(path.resolve(__dirname, '../react-ui/build', 'index.html'));
|
||||||
});
|
});
|
||||||
|
|
||||||
app.listen(PORT, function () {
|
app.listen(PORT, function () {
|
||||||
console.log(`Listening on port ${PORT}`);
|
console.error(`Node cluster worker ${process.pid}: listening on port ${PORT}`);
|
||||||
});
|
});
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user