节点帮助

重试 Node.js(开发人员如何工作)

发布 2024年六月6日
分享:

中的 "重试 "一词 Node.js 描述了一个模块,该模块由 Node.js 核心库提供,可在操作失败后更轻松地重试操作。在管理网络请求或任何其他可能因网络错误或问题、服务器中断或超时等临时故障而失败的操作时,该模块尤其有用。

重试模块提供了一个多功能、可配置的 API,使重试不成功任务的过程变得更简单。开发人员可以通过它指定重试行为和策略,如重试次数、重试间隔等待时间以及重试应在何种情况下进行。

瞬时生成 PDF 是动态在线开发世界的普遍需要。在创建发票、报告或证书时,Node.js 开发人员经常使用 IronPDF 等软件包。

然而,在实际情况中,网络问题、服务器中断或其他临时错误都可能导致生成 PDF 的尝试失败。在这种情况下,添加重试方法对于保证稳健性和可靠性至关重要。在本文章中,我们将探讨在 IronPDF 中添加 User-Retry 模式如何帮助 Node.js 开发人员提高 PDF 创建的可靠性。

了解用户重试模式

用户重试模式是软件开发中的一种弹性技术,用于处理操作过程中可能出现的临时问题,如网络请求或访问远程资源。它也被称为指数后退策略,或延迟递增重试。这种模式对分布式系统特别有用,因为在分布式系统中,网络问题(如瞬间资源争用)、服务器不可用响应数据或网络拥塞等多种因素都可能导致故障。

User-Retry 如何工作

第一次尝试: 尝试执行操作。如果操作成功,则业务照常进行。另一方面,如果程序因临时错误而失败,则会启动重试机制。

重试延迟越来越长: 系统会稍作停顿,然后再次尝试不成功的操作,而不是立即执行。每次尝试重试,重试延迟时间通常都会变长。这种延迟降低了过度消耗资源的可能性,并使系统能够从临时问题中恢复。

指数延迟(Exponential Backoff): 这种方法是计算重试延迟的常用方法,每次重试的间隔时间都以指数形式增加。例如,延迟可能从几毫秒开始,每次重试间隔时间增加两毫秒。这种指数式增长允许资源愈合,并阻止系统不停地对其进行攻击。

最大重试次数: 在操作成功或达到最大重试次数之前,都会执行重试程序。例如,通过设置最大重试次数限制,可以防止系统处理过多请求并无休止地重试,否则会导致资源耗尽或停机时间延长。

使用用户重试的好处

增强弹性:使用用户重试模式后,系统对暂时性错误的复原能力会更强。它们不需要人类的帮助,就能从挫折中优雅地恢复过来。

减轻负担 实施重试: 通过延长重试间隔时间,减轻目标资源的负担,减少系统失败的尝试次数。这就增强了系统的整体稳定性,并降低了级联故障的可能性。

更快的恢复: 通过逐步改变重试间隔,指数后备可使系统更快地从临时问题中恢复。随着时间间隔的延长,重试成功的几率也会增加,从而加快恢复速度。

改善用户体验: 使用 User-Retry 的应用程序时,用户遇到的故障和延迟更少。通过对临时故障的透明管理,该系统可为用户提供更无缝、更可靠的使用体验。

创建并使用重试节点 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 模块,因为它已包含在 Node.JS 的核心库中。

实施重试逻辑

下面是一些示例 Node.js 代码的示例实现,向您展示如何使用重试模块构建重试逻辑。在此示例代码中,进行了一次等待时间 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 文档;也可以在现有文档中添加文本、图像和形状,从已有文档中提取文本和图像,以及将 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

必须先使用 npm 安装 IronPDF 库。在使用 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 提供了一种可靠的方法。通过使用诸如ync-retry 等库以及 IronPDF 用于 PDF 创建和操作的强大功能,开发人员可以确保涉及生成 PDF 的流程不会出现临时错误和网络问题。

当 IronPDF 和重试逻辑相结合时,应用程序可以自动重试操作,延迟时间越来越长,从而从容地容忍 PDF 生成过程中的故障。这就增加了有效完成涉及创建 PDF 的任务的可能性,即使在困难的网络环境或高流量的情况下也是如此。

IronPDF 作为包含终身许可证的套餐,价格合理。该套餐价值不菲,许多系统的售价仅为 749 美元。它为许可证持有者提供全天候在线工程支持。请访问 网站 了解有关指控的更多信息。请访问 网站 了解有关 Iron Software 产品的更多信息。

< 前一页
Axios Retry NPM(它如何为开发者工作)
下一步 >
JavaScript 等待5秒(开发人员如何使用)

准备开始了吗? 版本: 2024.9 刚刚发布

免费 npm 安装 查看许可证 >