Skip to main content

Cluster

When to use the cluster module?

  • High availability of services
  • Little to no downtime
  • Basic scalability based on demand

适用于小项目以及不想去接触 docker 等容器技术和设置的情况。

packages

Commands

npx loadtest -n 1200 -c 400 -k http://localhost:3000/heavy
npx pm2 start index.js # Use after node primary.js

Example withou cluster

Start commmand

node index.js
index.js
import express from "express";

const port = 3000;
const app = express();

app.get("/heavy", (req, res) => {
let total = 0;
for (let i = 0; i < 50_000_000_000; i++) {
total++;
}
res.send(`The result of the CPU intensive task is ${total}\n`);
});

app.listen(port, () => {
console.log(`App listening on port ${port}`);
console.log(`worker pid=${process.pid}`);
});

Example with cluster

Start commmand

node primary.js
primary.js
import cluster from "cluster";
import os from "os";
import { dirname } from "path";
import { fileURLToPath } from "url";

const __dirname = dirname(fileURLToPath(import.meta.url));

const cpuCount = os.cpus().length;

console.log(`Tthe total number of CPUs is ${cpuCount}`);
console.log(`Primary pid=${processs.pid}`);
cluster.setupPrimary({
exec: __dirname + "/index.js",
});

for (let i = 0; i < cpuCount; i++) {
cluster.fork();
}

cluster.on("exist", (worker, code, signal) => {
console.log(`worker ${worker.process.pid} has been killed`);
console.log("Starting another worker");
cluster.fork();
});