在 Linux 系统中配置 Node.js 应用以处理并发,可以通过以下几种方法来实现:
cluster 模块Node.js 的 cluster 模块允许你创建多个工作进程,每个进程都可以处理请求,从而提高并发处理能力。
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(8000);
console.log(`Worker ${process.pid} started`);
}
PM2 是一个进程管理器,可以帮助你管理和保持 Node.js 应用的在线状态,并且可以轻松地处理并发。
npm install pm2 -g
pm2 start app.js -i max
-i max 参数会根据 CPU 核心数自动启动相应数量的工作进程。
Nginx 可以作为反向代理服务器,将请求分发到多个 Node.js 实例,从而提高并发处理能力。
sudo apt-get update
sudo apt-get install nginx
编辑 Nginx 配置文件(通常位于 /etc/nginx/sites-available/default),添加以下内容:
server {
listen 80;
server_name yourdomain.com;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
sudo systemctl restart nginx
除了 Nginx,你还可以使用其他负载均衡器(如 HAProxy、Traefik 等)来分发请求到多个 Node.js 实例。
除了上述方法,还可以通过优化 Node.js 应用来提高并发处理能力:
通过这些方法,你可以在 Linux 系统中有效地配置 Node.js 应用以处理并发请求。