在Ubuntu上使用Node.js处理并发请求,可以通过以下几种方式来实现:
Node.js是基于事件驱动和非阻塞I/O模型的,因此它天生适合处理并发请求。你可以使用http
模块或者更高级的框架如Express
来创建HTTP服务器。
http
模块):const http = require('http');
const server = http.createServer((req, res) => {
console.log('Request received at', Date.now());
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
cluster
模块Node.js的cluster
模块允许你创建多个工作进程,每个进程都可以处理请求,从而提高并发处理能力。
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
进行进程管理PM2
是一个流行的Node.js进程管理器,可以帮助你管理和扩展Node.js应用程序。
PM2
:npm install pm2 -g
pm2 start app.js -i max
-i max
参数会根据CPU核心数自动启动相应数量的工作进程。
Nginx
作为反向代理你可以使用Nginx
作为反向代理服务器,将请求分发到多个Node.js实例,从而提高并发处理能力。
Nginx
:sudo apt update
sudo apt 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;
}
}
Nginx
:sudo systemctl restart nginx
Redis
进行任务队列对于一些需要长时间处理的任务,可以使用Redis
作为任务队列,将任务分发到多个Node.js实例进行处理。
Redis
:sudo apt update
sudo apt install redis-server
ioredis
库连接Redis
:const Redis = require('ioredis');
const redis = new Redis();
redis.set('task:1', 'Task 1');
redis.set('task:2', 'Task 2');
redis.lrange('task:1', 0, -1, (err, tasks) => {
if (err) throw err;
console.log(tasks);
});
通过以上几种方式,你可以在Ubuntu上有效地使用Node.js处理并发请求。选择哪种方式取决于你的具体需求和应用场景。