首页  >  文章  >  web前端  >  使用工作线程增强 Node.js 服务器性能

使用工作线程增强 Node.js 服务器性能

PHPz
PHPz原创
2024-08-30 18:33:021031浏览

场景

在我们深入研究工作线程之前,让我们考虑一些场景......

假设客户端将一个大文件上传到服务器,该文件需要修改或涉及在后台处理数千个数据点。如果服务器等待此任务完成,则客户端将处于等待状态并且无法探索其他功能。想象一下,如果客户必须等待 5 分钟而无法执行任何其他操作 - 这将是令人沮丧的并且远不用户友好!

考虑另一种情况,您上传个人资料图片,并且需要很长时间来处理、转换并存储在数据库中。在此期间,如果服务器阻止您执行其他任务,则会显着降低用户体验。

在第一种情况下,如果服务器允许您在文件仍在处理的同时探索其他功能不是更好吗?这样,您就不必等待(因为服务器不会阻止您),从而获得更流畅的体验。

第二种情况,如果图像处理发生在后台,让您无需等待就可以继续使用其他功能怎么办?

解决方案

那么,在这些场景下,有什么有效的方法来优化系统的性能呢?虽然有多种方法,但使用工作线程是一个很好的解决方案。工作线程是在 Node.js 版本 10 中引入的,对于并行执行 CPU 密集型任务特别有用,可减少主 CPU 的负载。
工作线程在后台运行,创建一个单独的线程来处理密集计算而不阻塞主线程,从而允许服务器保持对其他任务的响应。虽然 JavaScript 传统上是一种单线程语言,而 Node.js 在单线程环境中运行,但工作线程通过在多个线程之间分配操作来实现多线程。这种并行执行优化了资源使用并显着减少了处理时间。

Enhance Node.js Server Performance with Worker Threads

worker_thread的实现:

今天我们将使用默认包worker_threads 实现一个简单的nodejs 应用程序。首先创建一个执行简单 get 请求的 Express 服务器。

首先初始化项目:

$ npm init -y

安装express模块​​和nodemon:

$ npm 我表达nodemon

创建一个在端口 3000 上运行的简单 Nodejs 服务器。

Import express from ‘express’;
const app = express();
const port = 3000;


// Basic endpoint to test server
app.get(‘/’, (req, res) => {
   res.send(‘Hello World!’);
});


app.listen(port, () => console.log(`Server running on port ${port}`));

这里我们创建了一个将在端口 3000 上运行的服务器。
要运行,我们需要修改 package.json 文件。
如下添加 type as module 以获得 ES6 模块。在脚本部分也进行如下修改。

{
 "name": "worker_express",
 "version": "1.0.0",
 "description": "",
 "main": "index.js",
 "type": "module",
 "scripts": {
   "test": "echo \"Error: no test specified\" && exit 1",
   "start": "node index.js",
   "dev": "nodemon index.js"
 },
 "keywords": [],
 "author": "",
 "license": "ISC",
 "dependencies": {
   "dotenv": "^16.4.5",
   "express": "^4.19.2",
   "nodemon": "^3.1.4"
 }
}

现在让我们使用 nodemon 以开发模式运行我们的应用程序:

$ npm run dev

您将看到消息 Server running on port 3000。现在转到 localhost:3000,您可以看到 Hello World!到目前为止,我们只做了一个简单的 Nodejs Express 服务器。

现在让我们创建另一个名为 service.js 的文件
在这里,我们可以创建一个斐波那契序列函数,用于查找第 n 个数字斐波那契序列。

// service.js
function fibonacci(n) {
   if (n <= 1) return 1;
   return fibonacci(n-1) + fibonacci(n-2);
}


export default fibonacci;

现在让我们向 index.js 文件添加另一个 api 端点,并从 service.js 文件调用 fibonacci 函数。我们以计算第 40 个斐波那契数为例。

import fibonacci from "./service.js";


// Fibonacci endpoint
app.get('/fibonacci', (req, res) => {
   fibonacci(40)
   res.send('fibonacci called');
})

如果你点击 URL http://localhost:3000/fibonacci,你会发现它有点延迟,让你等待。延迟时间取决于计算。

Enhance Node.js Server Performance with Worker Threads

您可以通过注释该函数再试一次,您会发现它花费的时间更少,大约是毫秒。

Enhance Node.js Server Performance with Worker Threads

在这种情况下,您可能需要执行其他繁重的操作,这些操作既耗时又会降低性能。

这种情况下,我们可以使用worker_threads模块,该模块从Node.js版本10开始就默认可用。现在我们修改代码来应用worker_threads,看看效果。

从node js默认包worker_thread导入Worker。

import { Worker } from "worker_threads";

现在修改 api 端点,如下所示。

// Endpoint using worker thread for CPU-intensive task
app.get('/fibonacci', (req, res) => {
   const worker = new Worker('./service.js', {workerData: 40});

   // Handle messages from worker thread
   worker.on('message', (resolve) => console.log(resolve));


   res.send('fibonacci called');
})

这里,我们创建了一个worker实例,并将文件名service.js设置为第一个参数,第二个参数通过workerData传递参数。您可以将workerData参数更改为任何其他数据,而不是40。

worker.on(‘message’, ….) This sets up an event listener on the worker for the ‘message’ event. The message event is emitted by the worker when it sends data back to the main thread using parentrPort.postMessage(...).
(resolve) => console.log(resolve) this is a callback function that will be executed when the worker sends back the data after operation. The received message(data) is passed to this function as the resolve parameter.

Now let’s update our service.js file.

import { workerData, parentPort } from 'worker_threads';


// Function to compute Fibonacci sequence
function fibonacci(n) {
   if (n <= 1) return 1;
   return fibonacci(n-1) + fibonacci(n-2);
}


// Compute Fibonacci using workerData
const fibonacciAt =  fibonacci(workerData);


// Send result back to the main thread
parentPort.postMessage(fibonacciAt);

Here, we import workerData and parentPort, which allow us to receive the data sent through workerData and return the result via the postMessage method of parentPort, both imported from worker_threads.

Test the Setup:
Now, send a request to http://localhost:3000/fibonacci and notice that the server no longer blocks the main thread. The time-consuming operation occurs in the background on a separate thread, significantly reducing the response time and improving user experience.

Enhance Node.js Server Performance with Worker Threads

Here is the source code in github.

以上是使用工作线程增强 Node.js 服务器性能的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn