https://blog.appsignal.com/2021/02/03/improving-node-application-performance-with-clustering.html
https://nodejs.org/api/cluster.html
const cluster = require("cluster");
const http = require("http");
const numCPUs = require("os").cpus().length;
if (cluster.isMaster) {
console.log(`Primary ${process.pid} is running`);
// Fork workers.
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on("exit", (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died`);
});
} else {
// Workers can share any TCP connection
// In this case it is an HTTP server
http
.createServer((req, res) => {
res.writeHead(200);
res.end("hello world\n");
})
.listen(8000);
console.log(`Worker ${process.pid} started`);
}
Node性能优化, 集群, 多进程, 负载均衡, 应用性能
通过Node.js集群提升应用性能,利用多核CPU优化HTTP服务器,实现负载均衡和高效处理请求。