ubuntu

如何在Ubuntu上使用Node.js实现并发处理

小樊
42
2025-10-18 05:13:47
栏目: 编程语言

在Ubuntu上使用Node.js实现并发处理,可以通过以下几种方式:

1. 使用cluster模块

Node.js的cluster模块允许你创建多个工作进程,这些进程可以共享同一个服务器端口。这样可以充分利用多核CPU的性能。

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

2. 使用worker_threads模块

Node.js的worker_threads模块允许你在单个Node.js进程中创建多个线程。这对于CPU密集型任务非常有用。

const { Worker, isMainThread, parentPort } = require('worker_threads');

if (isMainThread) {
  // This code is executed in the main thread
  const worker = new Worker(__filename);
  worker.on('message', (message) => {
    console.log('Message from worker:', message);
  });
} else {
  // This code is executed in the worker thread
  parentPort.postMessage('Hello from worker!');
}

3. 使用child_process模块

Node.js的child_process模块允许你创建子进程来执行其他任务。你可以使用spawnexecfork方法。

const { spawn } = require('child_process');

const child = spawn('ls', ['-lh', '/usr']);

child.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});

child.stderr.on('data', (data) => {
  console.error(`stderr: ${data}`);
});

child.on('close', (code) => {
  console.log(`child process exited with code ${code}`);
});

4. 使用异步编程

Node.js的异步编程模型(基于回调、Promise和async/await)本身就支持并发处理。通过合理使用这些特性,可以有效地处理并发请求。

const fs = require('fs').promises;

async function readFile(filePath) {
  try {
    const data = await fs.readFile(filePath, 'utf8');
    console.log(data);
  } catch (err) {
    console.error(err);
  }
}

readFile('example.txt');
readFile('another-example.txt');

5. 使用第三方库

还有一些第三方库可以帮助你实现并发处理,例如:

const pLimit = require('p-limit');

const limit = pLimit(2); // 限制并发数为2

const promises = [
  limit(() => fetchDataFromAPI('https://api.example.com/data1')),
  limit(() => fetchDataFromAPI('https://api.example.com/data2')),
  limit(() => fetchDataFromAPI('https://api.example.com/data3'))
];

Promise.all(promises).then(results => {
  console.log(results);
});

通过以上几种方式,你可以在Ubuntu上使用Node.js实现高效的并发处理。选择哪种方式取决于你的具体需求和应用场景。

0
看了该问题的人还看了