節點幫助

重試 Node.js(開發人員的運作方式)

發佈 2024年6月6日
分享:

“重試”一詞在 Node.js 描述了一個模組,使得在操作失敗後重試的過程變得更容易,並由 Node.js 核心庫提供。在處理網路請求或其他因臨時失敗如網路錯誤或問題、伺服器停機或超時等原因而失敗的操作時,這個模組特別有用。

重試模組提供了一個靈活且可配置的 API,使重試失敗任務的過程變得更簡單。它允許開發者指定重試的行為和策略,例如重試次數、重試之間的間隔等待時間和應該發生重試的情況。

即時 PDF 生成是網路開發動態世界中的一個常見需求。在創建發票、報告或證書時,Node.js 開發者經常使用像 IronPDF 這樣的包。

然而,在實際情況下,生成 PDF 的失敗嘗試可能是由於網路問題、伺服器停機或其他臨時錯誤造成的。在這類情況下,增加重試方法變得至關重要,以確保健壯性和可靠性。本文探討了如何將用戶重試模式添加到 IronPDF,幫助 Node.js 開發者提高 PDF 創建的可靠性。

瞭解使用者重試模式

使用者重試模式是一種在軟體開發中用來處理操作過程中可能出現的臨時問題的彈性技術,例如網路請求或存取遠程資源。這種模式也被稱為指數退避策略,或逐漸延遲重試。此模式對於分散式系統特別有用,因為在這些系統中,許多因素如網絡問題、暫時性資源爭用、伺服器不可用回應資料、或網絡擁堵等可能會導致失敗。

使用者重試機制如何運作

首次嘗試:嘗試進行操作。如果成功,則照常進行業務操作。另一方面,如果程序因暫時錯誤而失敗,則啟動重試機制。

增加延遲的重試:系統在再次嘗試失敗的操作之前會暫停一小段時間,而不是馬上重試。每次嘗試重試時,重試延遲通常會變長。這種延遲減少了資源過載的可能性,並使系統能夠從暫時的問題中恢復。

指數回退:這種方法通過每次重試嘗試之間的間隔指數增加來計算重試延遲是流行的方法。例如,延遲可能從幾毫秒開始,每次重試重新嘗試時增加兩倍。這種指數增長允許資源恢復並阻止系統不停地連續嘗試。

最大重試次數:直到操作成功或達到最大重試次數為止,重試程序將繼續進行。通過設置最大重試限制,例如,您可以阻止系統發出過多的請求並無休止地重試,這可能導致資源耗盡或長期停機。

使用用戶重試的好處

增強的韌性:使用用戶重試模式後,系統對暫時性錯誤變得更加韌性強。他們不需要人工協助即可優雅地從挫折中恢復。

減少實施重試的負擔:通過使用較長的重試間隔,目標資源上的負擔和系統嘗試失敗的次數都會減少。這增強了系統的整體穩定性,並降低了連鎖故障的可能性。

更快的恢復:通過逐步調整重試間隔,指數退避能使系統更快地從暫時性問題中恢復。由於間隔較長,成功重試的機會增加,從而更快地恢復。

改進的用戶體驗:使用用戶重試的應用程式時,使用者遇到的卡頓和延遲較少。通過透明管理暫時性故障,系統維持更無縫和可靠的用戶體驗。

建立並使用重試 Node.js

重試模組是 Node.js 的主要模組之一,使在 Node.js 中開始重試任務變得簡單。通過簡化重試邏輯的開發,這個模組可以更輕鬆地處理在網路請求或其他非同步處理過程中可能發生的臨時故障。以下是一個關於實現重試邏輯的詳細教程,以及如何在 Node.js 中實現重試邏輯:

安裝 Node.js

如果您還沒有安裝 Node.js,您可以從 下載並安裝它。 官方網站.

建立一個 Node.js 專案

使用終端機或命令提示字元,為您的專案創建一個新目錄並進入其中:

mkdir retry-example
cd retry-example
mkdir retry-example
cd retry-example
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'mkdir retry-example cd retry-example
VB   C#

通過執行以下操作設置一個全新的Node.JSON專案:

npm init -y
npm init -y
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'npm init -y
VB   C#

這將產生一個包。在專案目錄中有一個 JSON 文件。

安裝 retry 模組

不需要單獨安裝 retry 模組,因為它已經包含在 Node.JS 的核心庫中。

實作重試邏輯

以下是一個範例 Node.js 代碼的實作示例,展示了如何使用 retry 模組來建立重試邏輯。在這個範例代碼中,進行了一個等待時間的 API 調用,如果因臨時錯誤而失敗,它將使用指數回退重試。

const retry = require('retry');
// Simulate a function that performs a network request with intermittent failures
function performNetworkRequest(callback) {
    // Simulate a network request that fails 50% of the time
    const success = Math.random() < 0.5;
    if (success) {
        callback(null, 'Request successful');
    } else {
        callback(new Error('Request failed'));
    }
}
// Define options for retrying the operation
const operationOptions = {
    retries: 3,             // Number of retry attempts
    factor: 2,              // Exponential backoff factor
    minTimeout: 1000,       // Initial retry delay in milliseconds
    maxTimeout: 60000,      // Maximum retry delay in milliseconds
    randomize: true         // Randomize retry delays
};
// Create a retry operation instance
const retryOperation = retry.operation(operationOptions);
// Execute the operation with retry logic
retryOperation.attempt(function(currentAttempt) {
    performNetworkRequest(function(err, result) {
        if (retryOperation.retry(err)) {
            // Retry the operation
            console.log(`Attempt ${currentAttempt}: Retrying operation...`);
            return;
        }
        // Operation succeeded or max retries reached
        if (err) {
            console.error('Operation failed after ' + currentAttempt + ' attempts:', err);
        } else {
            console.log('Operation succeeded:', result);
        }
    });
});
const retry = require('retry');
// Simulate a function that performs a network request with intermittent failures
function performNetworkRequest(callback) {
    // Simulate a network request that fails 50% of the time
    const success = Math.random() < 0.5;
    if (success) {
        callback(null, 'Request successful');
    } else {
        callback(new Error('Request failed'));
    }
}
// Define options for retrying the operation
const operationOptions = {
    retries: 3,             // Number of retry attempts
    factor: 2,              // Exponential backoff factor
    minTimeout: 1000,       // Initial retry delay in milliseconds
    maxTimeout: 60000,      // Maximum retry delay in milliseconds
    randomize: true         // Randomize retry delays
};
// Create a retry operation instance
const retryOperation = retry.operation(operationOptions);
// Execute the operation with retry logic
retryOperation.attempt(function(currentAttempt) {
    performNetworkRequest(function(err, result) {
        if (retryOperation.retry(err)) {
            // Retry the operation
            console.log(`Attempt ${currentAttempt}: Retrying operation...`);
            return;
        }
        // Operation succeeded or max retries reached
        if (err) {
            console.error('Operation failed after ' + currentAttempt + ' attempts:', err);
        } else {
            console.log('Operation succeeded:', result);
        }
    });
});
Private const retry = require( 'retry');
' Simulate a function that performs a network request with intermittent failures
Private Function performNetworkRequest(ByVal As callback) As [function]
	' Simulate a network request that fails 50% of the time
	const success = Math.random() < 0.5
	If success Then
		callback(Nothing, 'Request successful');
	Else
		callback(New [Error]( 'Request failed'));
	End If
End Function
' Define options for retrying the operation
Private const operationOptions = { retries: 3, factor: 2, minTimeout: 1000, maxTimeout: 60000, randomize: True }
' Create a retry operation instance
Private const retryOperation = retry.operation(operationOptions)
' Execute the operation with retry logic
retryOperation.attempt([function](currentAttempt) { performNetworkRequest([function](err, result) { if(retryOperation.retry(err)) { console.log(`Attempt ${currentAttempt}:= Retrying operation...`); Return; } if(err) { console.error( 'Operation failed after ' + currentAttempt + ' attempts:', err); } else { console.log('Operation succeeded:', result); } }); });
VB   C#

要使用文件的功能,我們必須在開頭包含重試模組。一個名為 performNetworkRequest 的模擬函數模擬網絡請求。隨機失敗率為 50%。重試操作的選項包含在 operationOptions 中。我們指定最大和最小重試延遲、重試次數、指數回退因子以及是否隨機化重試延遲。

使用 retry.operation()我們建構重試操作的實例,並將其餵給 operationOptions。我們在重試操作的嘗試回呼中使用 performNetworkRequest 方法。如果請求失敗且可以重試,我們將重試該操作。 (如retryOperation.retry所示(錯誤))如果 retryoperation 物件是否為重試行為,我們管理操作的成功或失敗。

入門

為了在 Python 網頁應用程式中建立 PDF,結合 IronPDF 和 Celery 可以非常有效。Celery 是一個分佈式任務隊列,可以讓您將耗時的任務從網頁應用程式中卸載到不同的工作流程,而 IronPDF 提供了創建、編輯和輸出 PDF 文件的能力。通過異步建立 PDF,IronPDF 與 Celery 的集成有助於提高您的應用程式的可擴展性和性能。

IronPDF 是什麼?

我們可以在應用程式內創建、修改和渲染 PDF 文件,使用這個流行的 IronPDFNode.js 圖書館。處理PDF有多種方式:您可以從HTML內容、照片或原始數據創建新的PDF文件;您也可以在現有的PDF文件上添加文字、圖片和形狀,從已有的PDF文件中提取文字和圖片,並將HTML頁面轉換為PDF。

IronPDF的簡單性和易用性是其主要優點之一。通過其用戶友好的API和豐富的文檔,開發人員可以迅速開始在Node.js JS應用內生成PDF。IronPDF的效率和速度是另一個幫助開發人員快速生成高質量PDF文件的特點。

IronPDF的幾個優點

  • 從HTML、圖片和原始數據生成PDF。
  • 從PDF文件中提取文字和圖片。
  • 在PDF文件中添加頁眉、頁腳和水印。
  • 使用密碼和加密來保護PDF文件。
  • 能夠電子填寫和簽署文件。

安裝 IronPDF

使用 pip 安裝 IronPDF 庫是第一步。

npm i @ironsoftware/ironpdf
npm i @ironsoftware/ironpdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'npm i @ironsoftware/ironpdf
VB   C#

導入和配置 IronPDF

IronPDF 資料庫的安裝必須先透過 npm 完成。在使用 IronPDF 進行 PDF 生成之前,您必須使用您的授權密鑰進行初始化。確保您已準備好 IronPDF 授權密鑰。

const IronPdf = require("@ironsoftware/ironpdf");
var config=IronPdf.IronPdfGlobalConfig
config.setConfig({licenseKey:''});
const PdfDocument=IronPdf.PdfDocument;
const IronPdf = require("@ironsoftware/ironpdf");
var config=IronPdf.IronPdfGlobalConfig
config.setConfig({licenseKey:''});
const PdfDocument=IronPdf.PdfDocument;
const IronPdf = require("@ironsoftware/ironpdf")
Dim config=IronPdf.IronPdfGlobalConfig config.setConfig({licenseKey: ''});
const PdfDocument=IronPdf.PdfDocument
VB   C#

定義 PDF 生成函數

然後,使用 IronPDF 定義一個用於生成 PDF 的函數。此函數應處理創建 PDF 的邏輯和解決任何潛在問題的完整代碼。

async function generatePdf(htmlContent) {
    try {
        const pdf = await PdfDocument.fromHtml(htmlContent);
        return pdf;
    } catch (error) {
        // Log or handle the error
        console.error("Error occurred during PDF generation:", error);
        throw error;
    }
}
async function generatePdf(htmlContent) {
    try {
        const pdf = await PdfDocument.fromHtml(htmlContent);
        return pdf;
    } catch (error) {
        // Log or handle the error
        console.error("Error occurred during PDF generation:", error);
        throw error;
    }
}
Async Function generatePdf(ByVal As htmlContent) As [function]
	Try
		const pdf = Await PdfDocument.fromHtml(htmlContent)
		Return pdf
	Catch e1 As [error]
		' Log or handle the error
		console.error("Error occurred during PDF generation:", [error])
		Throw [error]
	End Try
End Function
VB   C#

實作重試邏輯

現在,納入重試邏輯以便重試 PDF 生成 在使用 async-retry 函式庫失敗時調用函式。

const retry = require('async-retry');
async function retryGeneratePdf(htmlContent) {
    return await retry(async (bail, attempt) => {
        console.log(`Attempt ${attempt} to generate PDF`);
        return await generatePdf(htmlContent);
    }, {
        retries: 3, // Maximum number of retry attempts
        factor: 2, // Exponential backoff factor
        minTimeout: 1000, // Initial retry delay in milliseconds
        maxTimeout: 60000, // Maximum retry delay in milliseconds
        randomize: true // Randomize retry delays
    });
}
const retry = require('async-retry');
async function retryGeneratePdf(htmlContent) {
    return await retry(async (bail, attempt) => {
        console.log(`Attempt ${attempt} to generate PDF`);
        return await generatePdf(htmlContent);
    }, {
        retries: 3, // Maximum number of retry attempts
        factor: 2, // Exponential backoff factor
        minTimeout: 1000, // Initial retry delay in milliseconds
        maxTimeout: 60000, // Maximum retry delay in milliseconds
        randomize: true // Randomize retry delays
    });
}
Private const retry = require( 'async-retry');
Async Function retryGeneratePdf(ByVal As htmlContent) As [function]
	Return Await retry(Async Function(bail, attempt)
		console.log(`Attempt ${attempt} [to] generate PDF`)
		Return Await generatePdf(htmlContent)
	End Function,{
		retries:=3,
		factor:= 2,
		minTimeout:= 1000,
		maxTimeout:= 60000,
		randomize:= True
	})
End Function
VB   C#

使用重試邏輯生成PDF

現在,您可以使用 retryGeneratePdf 函數來創建帶有重試邏輯的 PDF。

const htmlContent = "<html><body><h1>Hello, IronPDF!</h1></body></html>";
retryGeneratePdf(htmlContent)
    .then(pdf => {
        // PDF generation succeeded
    await pdf.saveAs('output.pdf')
        console.log("PDF generated successfully");
        // Handle the generated PDF
    })
    .catch(error => {
        // PDF generation failed after retries
        console.error("Failed to generate PDF:", error);
    });
const htmlContent = "<html><body><h1>Hello, IronPDF!</h1></body></html>";
retryGeneratePdf(htmlContent)
    .then(pdf => {
        // PDF generation succeeded
    await pdf.saveAs('output.pdf')
        console.log("PDF generated successfully");
        // Handle the generated PDF
    })
    .catch(error => {
        // PDF generation failed after retries
        console.error("Failed to generate PDF:", error);
    });
Private const htmlContent = "<html><body><h1>Hello, IronPDF!</h1></body></html>"
'INSTANT VB WARNING: The following constructor is declared outside of its associated class:
'ORIGINAL LINE: retryGeneratePdf(htmlContent).then(pdf =>
Private Sub New()
	Await pdf.saveAs( 'output.pdf') console.log("PDF generated successfully");
End Sub
'INSTANT VB TODO TASK: Lambda expressions and anonymous methods are not converted by Instant VB if local variables of the outer method are referenced within the anonymous method:
).catch([error] =>
VB   C#

自訂重試邏輯: 你可以修改重試策略或處理重試邏輯中特定問題以符合你的需求。

錯誤處理: 為了解決在創建PDF或重試過程中出現的錯誤,實施適當的錯誤處理。

日誌記錄: 包含日誌記錄,以便跟踪故障和重試的過程,進行監控和除錯。

通過整合IronPDF與重試邏輯,你可以在Node.js應用程序中提高可靠性並優雅地處理PDF創建錯誤。

重试 Node.js(開發人員的工作方式):圖 1

結論

總而言之,將 IronPDF 與 Node.js 的重試邏輯結合起來,為線上應用程序生成 PDF 提供了一種牢固且可靠的方法。通過使用如 async-retry 這樣的庫和 IronPDF 用於 PDF 生成及操作的強大功能,開發者可以確保涉及 PDF 生成的過程可以抵抗臨時錯誤和網路問題。

當 IronPDF 和重試邏輯結合時,應用程序可以通過自動重試操作來優雅地容忍 PDF 生成過程中的失敗,並隨著延遲時間的增加進行重試。這增加了在困難的網路情況或高流量下,PDF 生成任務能夠有效完成的可能性。

IronPDF 以包裝形式提供終身許可證,價格實惠。這個套裝提供了極佳的價值,現僅售 $749 並適用於多個系統。此外,許可證持有人還可享受全天候的在線工程支持。請訪問 網站 了解更多有關收費的資訊,請訪問此 網站 了解有關 Iron Software 產品的更多資訊。

< 上一頁
Axios重试NPM(開發者如何使用)
下一個 >
JavaScript 等待5秒(開發人員如何使用)

準備開始了嗎? 版本: 2024.9 剛剛發布

免費 npm 安裝 查看許可證 >