在 CentOS 系统上使用 Node.js 处理并发请求,通常会采用以下几种方法和技术:
Node.js 的内置 HTTP 模块可以用来创建一个简单的 HTTP 服务器,该服务器可以处理并发请求。Node.js 的事件驱动和非阻塞 I/O 模型使其能够高效地处理大量并发连接。
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
Express 是一个流行的 Node.js Web 应用框架,它简化了 HTTP 服务器的创建和路由处理。Express 也利用了 Node.js 的非阻塞 I/O 特性来处理并发请求。
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
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 进程管理器,它可以管理多个 Node.js 应用实例,并提供负载均衡功能。
npm install pm2 -g
pm2 start app.js -i max
Nginx 是一个高性能的 HTTP 和反向代理服务器,它可以用来处理静态文件、负载均衡和 SSL/TLS 加密。将 Nginx 配置为 Node.js 应用的反向代理可以进一步提高并发处理能力。
server {
listen 80;
server_name example.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;
}
}
对于需要实时通信的应用,可以使用 WebSocket 技术。Node.js 有多个 WebSocket 库,如 ws
和 socket.io
,可以用来实现实时通信。
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send('something');
});
通过结合这些技术和方法,你可以在 CentOS 系统上使用 Node.js 高效地处理并发请求。