温馨提示×

Linux Node.js如何处理并发请求

小樊
48
2025-09-21 01:22:33
栏目: 编程语言

在Linux环境下使用Node.js处理并发请求,主要依赖于Node.js的非阻塞I/O和事件驱动特性。以下是一些关键点和最佳实践:

1. 非阻塞I/O

Node.js的核心是事件循环和非阻塞I/O操作。这意味着Node.js可以在等待一个I/O操作完成时继续执行其他任务,从而有效地处理并发请求。

const http = require('http');

const server = http.createServer((req, res) => {
  // 模拟非阻塞I/O操作
  setTimeout(() => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello World\n');
  }, 1000);
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});

2. 使用异步函数和Promise

使用异步函数和Promise可以更清晰地管理异步代码,避免回调地狱。

const http = require('http');

const server = http.createServer(async (req, res) => {
  try {
    const data = await fetchData(); // 假设fetchData是一个返回Promise的异步函数
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify(data));
  } catch (error) {
    res.writeHead(500, { 'Content-Type': 'text/plain' });
    res.end('Internal Server Error');
  }
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});

async function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve({ message: 'Data fetched successfully' });
    }, 1000);
  });
}

3. 使用集群模块

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`);
}

4. 使用负载均衡器

在生产环境中,通常会使用负载均衡器(如Nginx或HAProxy)来分发请求到多个Node.js实例,进一步提高并发处理能力。

5. 优化数据库访问

数据库访问通常是性能瓶颈之一。使用连接池、缓存和优化的查询可以显著提高性能。

const mysql = require('mysql');
const pool = mysql.createPool({
  connectionLimit: 10,
  host: 'localhost',
  user: 'user',
  password: 'password',
  database: 'database'
});

pool.getConnection((err, connection) => {
  if (err) throw err;
  connection.query('SELECT * FROM users', (error, results, fields) => {
    connection.release();
    if (error) throw error;
    console.log(results);
  });
});

6. 监控和日志

使用监控工具(如PM2、Prometheus和Grafana)来监控Node.js应用的性能和健康状况,并设置适当的日志记录。

通过以上方法,你可以在Linux环境下有效地使用Node.js处理并发请求。

0