在CentOS上配置Node.js的集群模式可以帮助你充分利用多核CPU的性能,提高应用的并发处理能力。以下是一个详细的步骤指南:
首先,确保你已经在CentOS上安装了Node.js。你可以使用NodeSource或直接从官网下载安装包。
# 添加NodeSource仓库
curl -sL https://rpm.nodesource.com/setup_14.x | sudo bash -
# 安装Node.js
sudo yum install -y nodejs
创建一个简单的Node.js应用,例如一个HTTP服务器。
// app.js
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200);
res.end('Hello World\n');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
Node.js的cluster
模块可以帮助你创建多个工作进程。
// cluster-app.js
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
console.log(`Master ${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(3000);
console.log(`Worker ${process.pid} started`);
}
使用node
命令运行你的集群应用。
node cluster-app.js
你可以使用浏览器或curl
命令来验证集群是否正常工作。
curl http://localhost:3000/
你应该会看到多次响应,每次请求可能由不同的工作进程处理。
你可以使用一些工具来监控和管理你的Node.js集群,例如:
首先,安装PM2:
sudo npm install pm2 -g
然后,使用PM2启动你的应用:
pm2 start cluster-app.js -i max
-i max
参数会根据CPU核心数自动启动相应数量的工作进程。
你可以使用以下命令查看集群状态:
pm2 status
或者查看日志:
pm2 logs
通过这些步骤,你可以在CentOS上成功配置Node.js的集群模式,并充分利用多核CPU的性能。