Created
January 4, 2023 01:30
-
-
Save luizcalaca/b62de230ace39b6d363039a716aa07da to your computer and use it in GitHub Desktop.
Node.js and cluster
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const express = require('express'); | |
| const app = express() | |
| const os = require ('os') | |
| const cluster = require ('cluster') | |
| const numCPU = os.cpus().length | |
| app.get('/heavy', (req, res)=> { | |
| counter = 0; | |
| for (let index = 0; index < 10000000000000; index++) { | |
| counter++ | |
| } | |
| res.status(200).json(counter) | |
| }) | |
| if (cluster.isMaster) { | |
| for (let index = 0; index < numCPU; index++) { | |
| cluster.fork() | |
| } | |
| cluster.on('exit', (worker, code, signal) => { | |
| console.log(`${worker.process.pid} died`); | |
| cluster.fork() | |
| }) | |
| }else{ | |
| app.listen(3737, () => { | |
| console.log(`server ${process.pid}`) | |
| }) | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment