Skip to content

Commit 6b07de8

Browse files
committed
feat: add app cluster
1 parent ab13677 commit 6b07de8

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

src/app-cluster.service.ts

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/* eslint-disable @typescript-eslint/ban-ts-comment */
2+
// @ts-nocheck
3+
import * as cluster from 'cluster';
4+
import * as os from 'os';
5+
import { Injectable } from '@nestjs/common';
6+
7+
const numCPUs = os.cpus().length;
8+
9+
@Injectable()
10+
export class AppClusterService {
11+
// eslint-disable-next-line @typescript-eslint/ban-types
12+
static clusterize(callback: Function): void {
13+
if (cluster.isMaster) {
14+
console.log(`Master server started on ${process.pid}`);
15+
for (let i = 0; i < numCPUs; i++) {
16+
cluster.fork();
17+
}
18+
cluster.on('exit', (worker, code, signal) => {
19+
console.log(`Worker ${worker.process.pid} died. Restarting`);
20+
cluster.fork();
21+
});
22+
} else {
23+
console.log(`Cluster server started on ${process.pid}`);
24+
callback();
25+
}
26+
}
27+
}

src/main.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { AppModule } from './app.module';
55
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
66
import fastifyHelmet from '@fastify/helmet';
77
import compression from '@fastify/compress';
8+
import { AppClusterService } from './app-cluster.service';
89

910
async function bootstrap() {
1011
const docGlobalPrefix = 'documentation';
@@ -64,4 +65,4 @@ async function bootstrap() {
6465
logger.log(`📑 API Documentation is running on: http://localhost:${port}/${docGlobalPrefix}`);
6566
}
6667

67-
bootstrap();
68+
AppClusterService.clusterize(bootstrap);

0 commit comments

Comments
 (0)