![]() |
Node.js's cluster module, which allows for the creation of multiple instances of a Node.js application to utilize multiple CPU cores effectively.
Cluster is following round-robin approach.
Workload is equally distribute in our servers and Handling traffic.
Example of Cluster with Node.js
const express = require('express');
const cluster = require('cluster');
const os = require('os');
const PORT = 3300; // Server port
const numCPUs = os.cpus().length; // Total CPU cores available
if (cluster.isPrimary) {
console.log(`Master process started with PID: ${process.pid}`);
// Fork workers for each CPU core
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
// Listen for worker exit and optionally restart
cluster.on('exit', (worker, code, signal) => {
console.log(`Worker ${worker.process.pid} exited. Starting a new worker...`);
cluster.fork(); // Optionally replace the dead worker
});
} else {
const app = express();
// Middleware to log requests
app.use((req, res, next) => {
console.log(`Request handled by process ${process.pid}`);
next();
});
// Example routes
app.get('/', (req, res) => {
res.send({
message: `Handled by process ${process.pid}`,
route: '/',
});
});
app.get('/about', (req, res) => {
res.send({
message: `Handled by process ${process.pid}`,
route: '/about',
});
});
app.get('/contact', (req, res) => {
res.send({
message: `Handled by process ${process.pid}`,
route: '/contact',
});
});
// Start the server
app.listen(PORT, () => {
console.log(`Worker ${process.pid} started. Listening on port ${PORT}`);
});
}
No comments:
Post a Comment