首頁 > web前端 > js教程 > 主體

使用工作執行緒增強 Node.js 伺服器效能

PHPz
發布: 2024-08-30 18:33:02
原創
1029 人瀏覽過

場景

在我們深入研究工作線程之前,讓我們考慮一些場景......

假設客戶端將一個大檔案上傳到伺服器,該檔案需要修改或涉及在後台處理數千個資料點。如果伺服器等待此任務完成,則用戶端將處於等待狀態並且無法探索其他功能。想像一下,如果客戶必須等待 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中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!