Node.js is a popular platform for developing scalable applications, but its single-threaded architecture can become a bottleneck in high-load situations. To make the most of the power of Node.js, clustering is an effective technique that allows you to use multiple CPU cores, improving the performance and responsiveness of your application.
First, create a new directory for your project and start a new Node.js project:
mkdir node-cluster
cd node-cluster
npm init -y
For this tutorial, you will only need Node.js itself, but we will use express to create a simple HTTP server. Install express with the following command:
npm install express
Create a file called server.js and add the following code:
const cluster = require('cluster'); const express = require('express'); const http = require('http'); const os = require('os'); const app = express(); const numCPUs = os.cpus().length; // Middleware para simular processamento intenso app.get('/', (req, res) => { let sum = 0; for (let i = 0; i < 1e7; i++) { sum += i; } res.send(`Soma: ${sum}, Processado pelo Worker: ${process.pid}`); }); // Lógica de clusterização if (cluster.isMaster) { console.log(`Master ${process.pid} is running`); // Cria um worker para cada núcleo de CPU for (let i = 0; i < numCPUs; i++) { cluster.fork(); } cluster.on('exit', (worker, code, signal) => { console.log(`Worker ${worker.process.pid} morreu`); }); } else { // Cada worker escuta na mesma porta const server = http.createServer(app); server.listen(3000, () => { console.log(`Worker ${process.pid} started`); }); }
The cluster configuration must be done according to the number of CPUs available on your machine or server. For example, if your server has 6 CPUs, it is ideal to create 6 workers to make the most of the available resources. Using more workers than CPU cores can lead to overload and decreased performance, while using fewer workers can result in underutilization of resources. It is recommended to test different configurations to find the ideal balance between performance and resource utilization.
Now you can run your application. Use the following command:
node server.js
If you follow the example you will see something similar to:
in your terminal
Master 12345 is running Worker 12346 started Worker 12347 started Worker 12348 started
To test the / route of your local server using curl, you can use the following command:
curl http://localhost:3000/
When you run the above command in the terminal, you should receive a response similar to this:
Soma: 49999995000000, Processado pelo Worker: 12348
The above is the detailed content of Creating Clustering in Node.js Applications. For more information, please follow other related articles on the PHP Chinese website!