Home > Web Front-end > JS Tutorial > body text

Creating Clustering in Node.js Applications

DDD
Release: 2024-11-02 09:37:02
Original
343 people have browsed it

Criando Clusterização em Aplicações Node.js

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.

Prerequisites

  • Node.js installed on your machine. You can download the latest version from nodejs.
  • Basic familiarity with JavaScript and Node.js.

Step 1: Create a New Node.js Project

First, create a new directory for your project and start a new Node.js project:

mkdir node-cluster
Copy after login
cd node-cluster
Copy after login
npm init -y
Copy after login

Step 2: Install Dependencies

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
Copy after login

Step 3: Create the Server with Clustering

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`);
  });
}
Copy after login

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.

Step 4: Run the Application

Now you can run your application. Use the following command:

node server.js
Copy after login

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
Copy after login

Step 5: Test the Application

To test the / route of your local server using curl, you can use the following command:

curl http://localhost:3000/
Copy after login

When you run the above command in the terminal, you should receive a response similar to this:

Soma: 49999995000000, Processado pelo Worker: 12348
Copy after login

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!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!