LoginSignup
2
0

More than 1 year has passed since last update.

NestJSクラスタ起動

Posted at

Nestのプロジェクト作成

npm i -g @nestjs/cli
nest new "プロジェクト名"

起動確認

yarn start

localhost:3000にアクセス
image.png

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}`;
  }
}

起動して確認

image.png
※自身のPCのコア数が4なので、4プロセス分forkされる

localhost:3000にアクセスし、複数プロセスで動いているのを確認

image.png
image.png
image.png

github

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0