Skip to content

Commit

Permalink
created cluster-manager
Browse files Browse the repository at this point in the history
  • Loading branch information
ksmooi committed Oct 27, 2024
1 parent 80cb7f6 commit 376dce6
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/apps/cluster_server/clusterManager.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// npx ts-node src/apps/cluster_server/clusterManager.ts

import cluster from 'cluster';
import os from 'os';
import http from 'http';

const port = process.env.PORT || 3000;
const numCPUs = os.cpus().length;

if (cluster.isPrimary) {
console.log(`Master ${process.pid} is running`);

// Fork workers for each CPU core
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}

cluster.on('exit', (worker, code, signal) => {
console.log(`Worker ${worker.process.pid} died. Forking a new one.`);
cluster.fork(); // Automatically restart the worker on failure
});
} else {
// Workers share the same TCP connection in this server
http.createServer((req, res) => {
res.writeHead(200);
res.end(`Hello from worker ${process.pid}\n`);
}).listen(port, () => {
console.log(`Worker ${process.pid} started`);
});
}

0 comments on commit 376dce6

Please sign in to comment.