server: run as cluster in production

This commit is contained in:
fantasticit 2022-05-22 20:40:55 +08:00
parent 6d561476b6
commit 6941a5a226
5 changed files with 35 additions and 3 deletions

View File

@ -0,0 +1,29 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
import { Injectable } from '@nestjs/common';
import * as cluster from 'cluster';
import * as os from 'os';
const numCPUs = os.cpus().length;
@Injectable()
export class AppClusterService {
static clusterize(callback): void {
// @ts-ignore
if (cluster.isMaster) {
console.log(`[think] 主进程 ${process.pid} 启动`);
for (let i = 0; i < numCPUs; i++) {
// @ts-ignore
cluster.fork();
}
// @ts-ignore
cluster.on('exit', (worker) => {
console.log(`[think] ,重启工作进程 ${worker.process.pid},重启中...`);
// @ts-ignore
cluster.fork();
});
} else {
console.log(`[think] 工作进程 ${process.pid} 启动`);
callback();
}
}
}

View File

@ -8,6 +8,7 @@ import { UserEntity } from '@entities/user.entity';
import { ViewEntity } from '@entities/view.entity';
import { WikiEntity } from '@entities/wiki.entity';
import { WikiUserEntity } from '@entities/wiki-user.entity';
import { IS_PRODUCTION } from '@helpers/env.helper';
import { getLogFileName, ONE_DAY } from '@helpers/log.helper';
import { CollectorModule } from '@modules/collector.module';
import { CommentModule } from '@modules/comment.module';
@ -61,7 +62,7 @@ const MODULES = [
isGlobal: true,
}),
ScheduleModule.forRoot(),
process.env.NODE_ENV === 'production' &&
IS_PRODUCTION &&
LoggerModule.forRoot({
pinoHttp: {
stream: pino.destination({

View File

@ -0,0 +1 @@
export const IS_PRODUCTION = process.env.NODE_ENV === 'production';

View File

@ -1,4 +1,5 @@
import { HttpResponseExceptionFilter } from '@exceptions/http-response.exception';
import { IS_PRODUCTION } from '@helpers/env.helper';
import { ConfigService } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import { ValidationPipe } from '@pipes/validation.pipe';
@ -8,6 +9,7 @@ import * as express from 'express';
import helmet from 'helmet';
import { AppModule } from './app.module';
import { AppClusterService } from './app-cluster.service';
async function bootstrap() {
const app = await NestFactory.create(AppModule, {
@ -30,4 +32,4 @@ async function bootstrap() {
console.log(`[think] 主服务启动成功,端口:${port}`);
}
bootstrap();
IS_PRODUCTION ? AppClusterService.clusterize(bootstrap) : bootstrap();

View File

@ -6,7 +6,6 @@ import { DocumentService } from '@services/document.service';
import { DocumentVersionService } from '@services/document-version.service';
import { TemplateService } from '@services/template.service';
import { OutUser, UserService } from '@services/user.service';
import { getConfig } from '@think/config';
import { DocumentStatus } from '@think/domains';
import * as lodash from 'lodash';
import * as Y from 'yjs';