Nestのプロジェクト作成
npm i -g @nestjs/cli
nest new "プロジェクト名"
起動確認
yarn start
main.tsの修正
main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as _cluster from 'cluster';
const cluster = _cluster as unknown as _cluster.Cluster;
import * as os from 'os';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
if (cluster.isPrimary) {
console.log(`Master server started on ${process.pid} cpu len: ${os.cpus().length}`);
// cpuの数分forkする
for (var i = 0; i < os.cpus().length; i++) {
console.log('cluster fork :', i);
cluster.fork();
}
} else {
console.log('boot strap')
bootstrap();
}
app.service.tsの修正
src/app.service.ts
import { Injectable } from '@nestjs/common';
import * as _cluster from 'cluster';
const cluster = _cluster as unknown as _cluster.Cluster;
@Injectable()
export class AppService {
getHello(): string {
console.log(cluster.worker.id)
return `Worker ID: ${cluster.worker?.id} PID: ${cluster.worker.process.pid}`;
}
}
起動して確認
localhost:3000にアクセスし、複数プロセスで動いているのを確認
github