@@ -8,6 +8,8 @@ import { swagger } from '@middleware/swagger.md';
88import { slowTrace } from '@middleware/slow-trace.md' ;
99import { httpLogger } from '@middleware/http-logger.md' ;
1010import { logger } from '@services/logger' ;
11+ import cluster from 'node:cluster' ;
12+ import { cpus } from 'node:os' ;
1113
1214export const app = new WebApp ( {
1315 language : 'zh_CN' ,
@@ -24,18 +26,36 @@ export const app = new WebApp({
2426 ] ,
2527} ) ;
2628
27- app . on ( 'error ' , ( err , ctx ) => {
29+ process . on ( 'uncaughtException ' , ( err ) => {
2830 logger . error ( err . stack ! ) ;
29- ctx . response . body = {
30- status : ctx . response . statusCode ,
31- message : ctx . response . body ,
32- } ;
3331} ) ;
3432
35- const port = process . env [ 'PORT' ] || 3000 ;
36- app . listen ( port , ( ) => {
37- console . log ( `服务已启动,点击 http://localhost:${ port } 访问` ) ;
38- } ) ;
33+ if ( cluster . isWorker ) {
34+ app . on ( 'error' , ( err , ctx ) => {
35+ logger . error ( err . stack ! ) ;
36+ ctx . response . body = {
37+ status : ctx . response . statusCode ,
38+ message : ctx . response . body ,
39+ } ;
40+ } ) ;
41+ app . listen ( process . env [ 'PORT' ] || 3000 ) ;
42+ }
43+
44+ if ( cluster . isPrimary ) {
45+ for ( let i = cpus ( ) . length ; i -- > 0 ; ) {
46+ cluster . fork ( ) ;
47+ }
48+
49+ cluster
50+ . on ( 'listening' , ( worker , address ) => {
51+ const href = `http://${ address . address || 'localhost' } :${ address . port } ` ;
52+ logger . info ( `Worker ${ worker . id } is listening ${ href } ` ) ;
53+ } )
54+ . on ( 'exit' , ( worker , code , signal ) => {
55+ logger . error ( `Worker ${ worker . id } exit with code '${ code } ' and signal '${ signal } '` ) ;
56+ cluster . fork ( ) ;
57+ } ) ;
58+ }
3959
4060declare module '@aomex/web' {
4161 namespace WebApp {
0 commit comments