Skip to content

Commit

Permalink
Merge pull request #21 from oasysgames/feature/multi_processing
Browse files Browse the repository at this point in the history
enable to set worker_count to use multi_processing
  • Loading branch information
Tsuyoshi-Ishikawa authored Mar 16, 2023
2 parents 968a204 + 9861c60 commit e4ee2f6
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
10 changes: 9 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -275,4 +275,12 @@ The default body parse limit is 512kb.

```bash
MAX_BODY_BYTE_SIZE=1048576 # 1048576 byte is 1MB.
```
```

## Multi Processing
If you want to build proxy in multi-process, set worker count to environment variables.
The default worker count is 1.

```bash
CLUSTER_PROCESS=4
```
31 changes: 30 additions & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,13 @@ import { NestFactory } from '@nestjs/core';
import { ValidationPipe } from '@nestjs/common';
import { AppModule } from 'src/app.module';
import { json } from 'body-parser';
import * as _cluster from 'cluster';
import { cpus } from 'os';

const cluster = _cluster as unknown as _cluster.Cluster;
const workerCount = process.env.CLUSTER_PROCESS
? parseInt(process.env.CLUSTER_PROCESS, 10)
: 1;

async function bootstrap() {
const app = await NestFactory.create(AppModule);
Expand All @@ -20,4 +27,26 @@ async function bootstrap() {
});
await app.listen(process.env.PORT ? parseInt(process.env.PORT, 10) : 3000);
}
bootstrap();

if (cluster.isPrimary) {
const workerLimit = cpus().length;
if (workerCount > workerLimit)
throw new Error(
`cluster process limit is ${workerLimit}. CLUSTER_PROCESS is over ${workerLimit}`,
);

for (let i = 0; i < workerCount; i++) {
console.log('cluster fork :', i);
cluster.fork();
}

cluster.on('exit', (worker, code, signal) => {
console.log(
`Worker ${worker.process.pid} died with code(${code}) and signal(${signal}). Restarting...`,
);
cluster.fork();
});
} else {
console.log('worker pid is', cluster.worker?.process.pid);
bootstrap();
}

0 comments on commit e4ee2f6

Please sign in to comment.