Saltar al pie de página
.NET AYUDA

.NET Core Polly (Cómo funciona para desarrolladores)

Polly is a .NET resilience strategies and transient fault handling library, allowing developers to express resilience policies such as Retry policy, Circuit Breakers, Timeout, Bulkhead Isolation policy, and Fallback. Polly targets ASP.NET Core, making it a vital tool for .NET Core resilience. Polly is thread-safe and supports handling multiple concurrent requests with successful responses.

This tutorial will provide more details about the transient fault handling .NET library, Polly, and how to use it with IronPDF in an ASP.NET Core application. We'll take a deep dive into each aspect of Polly, explain the mechanics of the circuit breaker pattern, discuss bulkhead isolation and timeouts, and show how to handle specific exceptions or failing services with failure responses in a controlled, thread-safe manner.

Polly Policies

Transient faults often occur when your application tries to connect with a web service through an HTTP request, database, or other external resources. These faults, like network failures, temporary connectivity issues, or timeouts, are brief and typically correct themselves after a short time.

Polly manages these transient faults by applying different strategies and expressing policies like Retry Policy, advanced Circuit Breaker Policy, Timeout Policy, Fallback Policy, and Bulkhead Isolation Policy.

Retry Policy

Retry Policy automatically retries failed concurrent requests using retry logic. It can be configured to retry forever or do automatic retries for a certain number of times, and it can wait a set time interval between retries or use an exponential back-off.

Circuit Breaker

The Circuit Breaker policy lets your system support a cancellation token for trying a particular service after a pre-configured threshold of failed requests. The Circuit Breaker strategy is analogous to chaos engineering or a ship closing watertight doors to localize damage: one fault won't sink the whole ship.

Timeout Policy

Timeout policy enforces a maximum time that a particular piece of .NET resilience code can execute. It comes in two flavors: optimistic timeout and pessimistic timeout.

Fallback Policy

Fallback policy is used to provide a substitute value or behavior in the event of a failure. This policy can be useful when a failing service should not halt the entire process.

Bulkhead Isolation

Bulkhead isolation is used to limit how many concurrent requests can be made to a specific operation, thereby limiting the potential for socket exhaustion and maintaining a controlled number of execution slots.

Cache Policy

The cache policy caches the successful response of an execution so that if the same execution is invoked again, Polly can return the distributed cache value.

Policy Wrap

Allows us to wrap multiple policies together, so they can work as a single unit.

Create and Configure Policies

Retry Policy

A retry policy is simple: when a specific exception or a fault occurs, Polly will try to execute the underlying delegate again. You can define how many times to retry, the time interval between retries, or use an exponential back-off strategy else it will retry forever. Here's an example:

// Retry policy for handling HttpRequestException with exponential back-off
var retryPolicy = Policy
    .Handle<HttpRequestException>()
    .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), 
    (exception, timeSpan, retryCount, context) =>
    {
        // This is the OnRetry delegate, where you can log or monitor failed requests
        Console.WriteLine($"Retry {retryCount} after {timeSpan}. Exception: {exception.Message}");
    });
// Retry policy for handling HttpRequestException with exponential back-off
var retryPolicy = Policy
    .Handle<HttpRequestException>()
    .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), 
    (exception, timeSpan, retryCount, context) =>
    {
        // This is the OnRetry delegate, where you can log or monitor failed requests
        Console.WriteLine($"Retry {retryCount} after {timeSpan}. Exception: {exception.Message}");
    });
' Retry policy for handling HttpRequestException with exponential back-off
Dim retryPolicy = Policy.Handle(Of HttpRequestException)().WaitAndRetryAsync(3, Function(retryAttempt) TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), Sub(exception, timeSpan, retryCount, context)
	Console.WriteLine($"Retry {retryCount} after {timeSpan}. Exception: {exception.Message}")
End Sub)
$vbLabelText   $csharpLabel

Circuit Breaker Policy

The Circuit Breaker policy lets the Polly library monitor for faults, and if the number of faults exceeds a configured threshold within a specified period, the circuit is "broken," and further requests are blocked for a specified time. This is called the 'open' state. After this time, the circuit enters a 'half-open' state, where it allows some traffic to check the health of the particular service. If these requests are successful and no faults occur, the circuit closes; otherwise, it opens again.

// Circuit breaker policy to handle failing requests with open and half-open states
var circuitBreakerPolicy = Policy
    .Handle<HttpRequestException>()
    .CircuitBreakerAsync(5, TimeSpan.FromMinutes(1));
// Circuit breaker policy to handle failing requests with open and half-open states
var circuitBreakerPolicy = Policy
    .Handle<HttpRequestException>()
    .CircuitBreakerAsync(5, TimeSpan.FromMinutes(1));
' Circuit breaker policy to handle failing requests with open and half-open states
Dim circuitBreakerPolicy = Policy.Handle(Of HttpRequestException)().CircuitBreakerAsync(5, TimeSpan.FromMinutes(1))
$vbLabelText   $csharpLabel

Timeout Policy

Timeout policies handle scenarios where a service isn't responding within a reasonable timeframe. Polly offers two types of timeouts: Optimistic and Pessimistic. An optimistic timeout works on a separate thread and cancels the underlying operation via a CancellationToken. A pessimistic timeout blocks the parent thread until the operation completes or the timeout period elapses.

// Timeout policy with a 30-second optimistic timeout
var timeoutPolicy = Policy.TimeoutAsync(30); // 30 seconds
// Timeout policy with a 30-second optimistic timeout
var timeoutPolicy = Policy.TimeoutAsync(30); // 30 seconds
' Timeout policy with a 30-second optimistic timeout
Dim timeoutPolicy = Policy.TimeoutAsync(30) ' 30 seconds
$vbLabelText   $csharpLabel

Bulkhead Isolation

Bulkhead Isolation is used to limit the number of concurrent actions against a particular service. It provides a way to isolate faults and prevent them from cascading. It also limits the load we place on our dependencies.

// Bulkhead isolation policy to limit concurrency and queue length
var bulkheadIsolationPolicy = Policy.BulkheadAsync(10, 20); // 10 concurrent actions, 20 queue slots
// Bulkhead isolation policy to limit concurrency and queue length
var bulkheadIsolationPolicy = Policy.BulkheadAsync(10, 20); // 10 concurrent actions, 20 queue slots
' Bulkhead isolation policy to limit concurrency and queue length
Dim bulkheadIsolationPolicy = Policy.BulkheadAsync(10, 20) ' 10 concurrent actions, 20 queue slots
$vbLabelText   $csharpLabel

Fallback Policy

Fallback policies are useful when you need to provide a default behavior or substitute value when all else fails.

// Fallback policy to provide a default result on failure
var fallbackPolicy = Policy
    .Handle<Exception>()
    .FallbackAsync<FallbackResult>(
        FallbackResult.SomethingWentWrong, 
        (exception, context) => 
        {
            Console.WriteLine($"Fallback triggered due to: {exception.Message}");
            return Task.CompletedTask;
        });
// Fallback policy to provide a default result on failure
var fallbackPolicy = Policy
    .Handle<Exception>()
    .FallbackAsync<FallbackResult>(
        FallbackResult.SomethingWentWrong, 
        (exception, context) => 
        {
            Console.WriteLine($"Fallback triggered due to: {exception.Message}");
            return Task.CompletedTask;
        });
' Fallback policy to provide a default result on failure
Dim fallbackPolicy = Policy.Handle(Of Exception)().FallbackAsync(Of FallbackResult)(FallbackResult.SomethingWentWrong, Function(exception, context)
			Console.WriteLine($"Fallback triggered due to: {exception.Message}")
			Return Task.CompletedTask
End Function)
$vbLabelText   $csharpLabel

Wrapping the Policies

Multiple policies can be combined flexibly using a PolicyWrap:

// Combining multiple policies using PolicyWrap
var policyWrap = Policy.WrapAsync(fallbackPolicy, retryPolicy, circuitBreakerPolicy, timeoutPolicy, bulkheadIsolationPolicy);
// Combining multiple policies using PolicyWrap
var policyWrap = Policy.WrapAsync(fallbackPolicy, retryPolicy, circuitBreakerPolicy, timeoutPolicy, bulkheadIsolationPolicy);
' Combining multiple policies using PolicyWrap
Dim policyWrap = Policy.WrapAsync(fallbackPolicy, retryPolicy, circuitBreakerPolicy, timeoutPolicy, bulkheadIsolationPolicy)
$vbLabelText   $csharpLabel

Getting Started

To begin using Polly with IronPDF, make sure you have Visual Studio installed and create a new Console Application project in .NET Core. Open the NuGet Package Manager Console in Visual Studio and install the Polly and IronPDF packages:

Install-Package Polly
Install-Package IronPdf

Using Polly with IronPDF Converting a URL to PDF

A prominent feature of IronPDF is its HTML to PDF capability, ensuring layouts and styles are intact. This function turns web content into PDFs, which is perfect for reports, invoices, and documentation. It supports converting HTML files, URLs, and HTML strings to PDFs.

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

Let's walk through an example of using Polly with IronPDF to convert a URL to PDF. Assume we have a web service that occasionally fails due to transient faults, and we want to handle those failures gracefully using Polly.

First, let's import the necessary namespaces in our Program.cs file:

using System;
using System.Threading.Tasks;
using Polly;
using Polly.Wrap;
using IronPdf;
using System;
using System.Threading.Tasks;
using Polly;
using Polly.Wrap;
using IronPdf;
Imports System
Imports System.Threading.Tasks
Imports Polly
Imports Polly.Wrap
Imports IronPdf
$vbLabelText   $csharpLabel

Next, we'll define our policies. In this example, we'll use a combination of retry and circuit breaker policies to handle failures:

// Retry policy with exponential backoff
var retryPolicy = Policy
    .Handle<Exception>()
    .WaitAndRetryAsync(3, i => TimeSpan.FromSeconds(2 * i));

// Circuit breaker policy to block requests after consecutive failures
var circuitBreakerPolicy = Policy
    .Handle<Exception>()
    .CircuitBreakerAsync(2, TimeSpan.FromSeconds(30));
// Retry policy with exponential backoff
var retryPolicy = Policy
    .Handle<Exception>()
    .WaitAndRetryAsync(3, i => TimeSpan.FromSeconds(2 * i));

// Circuit breaker policy to block requests after consecutive failures
var circuitBreakerPolicy = Policy
    .Handle<Exception>()
    .CircuitBreakerAsync(2, TimeSpan.FromSeconds(30));
' Retry policy with exponential backoff
Dim retryPolicy = Policy.Handle(Of Exception)().WaitAndRetryAsync(3, Function(i) TimeSpan.FromSeconds(2 * i))

' Circuit breaker policy to block requests after consecutive failures
Dim circuitBreakerPolicy = Policy.Handle(Of Exception)().CircuitBreakerAsync(2, TimeSpan.FromSeconds(30))
$vbLabelText   $csharpLabel

The retryPolicy will retry the failed request up to three times with an exponential backoff strategy, waiting 2 seconds, 4 seconds, and 8 seconds between retries. The circuitBreakerPolicy will open the circuit if two consecutive failures occur within a 30-second time interval.

Now, let's define our IronPDF code to convert a URL to a PDF:

var htmlToPdf = new ChromePdfRenderer();
var pdfBytes = await retryPolicy
    .WrapAsync(circuitBreakerPolicy)
    .ExecuteAsync(async () =>
    {
        Console.WriteLine("Attempting to convert URL to PDF...");
        var result = await htmlToPdf.RenderUrlAsPdfAsync("https://example.com");
        Console.WriteLine("Conversion successful!");
        return result;
    });

pdfBytes.SaveAs("output.pdf");
var htmlToPdf = new ChromePdfRenderer();
var pdfBytes = await retryPolicy
    .WrapAsync(circuitBreakerPolicy)
    .ExecuteAsync(async () =>
    {
        Console.WriteLine("Attempting to convert URL to PDF...");
        var result = await htmlToPdf.RenderUrlAsPdfAsync("https://example.com");
        Console.WriteLine("Conversion successful!");
        return result;
    });

pdfBytes.SaveAs("output.pdf");
Dim htmlToPdf = New ChromePdfRenderer()
Dim pdfBytes = Await retryPolicy.WrapAsync(circuitBreakerPolicy).ExecuteAsync(Async Function()
		Console.WriteLine("Attempting to convert URL to PDF...")
		Dim result = Await htmlToPdf.RenderUrlAsPdfAsync("https://example.com")
		Console.WriteLine("Conversion successful!")
		Return result
End Function)

pdfBytes.SaveAs("output.pdf")
$vbLabelText   $csharpLabel

In the above example code, we wrap our retryPolicy and circuitBreakerPolicy using the WrapAsync method. This allows us to apply multiple policies to new requests sequentially. The ExecuteAsync method executes the provided delegate, which in this code is the RenderUrlAsPdfAsync method from IronPDF.

By applying Polly policies, we ensure that our code is resilient to transient faults. If a request fails, Polly will automatically retry it according to the retry policy. If the number of consecutive failures crosses the pre-configured threshold, the circuit breaker policy will open the circuit, preventing further requests for a specified duration.

Test Cases for Polly Policies

To test the effectiveness of our Polly policies, let's simulate some failed requests. Modify the URL to a non-existent endpoint and add a few test cases:

var testUrls = new[]
{
    "https://ironpdf.com",
    "https://notexistingdomain.com/",
    "http://httpbin.org/delay/120"
};

foreach (var url in testUrls)
{
    try
    {
        var pdfBytes = await retryPolicy
            .WrapAsync(circuitBreakerPolicy)
            .ExecuteAsync(() => htmlToPdf.RenderUrlAsPdfAsync(url));

        pdfBytes.SaveAs($"{Guid.NewGuid()}.pdf");
        Console.WriteLine($"Successfully converted {url} to PDF.");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Failed to convert {url} to PDF: {ex.Message}");
    }
}
var testUrls = new[]
{
    "https://ironpdf.com",
    "https://notexistingdomain.com/",
    "http://httpbin.org/delay/120"
};

foreach (var url in testUrls)
{
    try
    {
        var pdfBytes = await retryPolicy
            .WrapAsync(circuitBreakerPolicy)
            .ExecuteAsync(() => htmlToPdf.RenderUrlAsPdfAsync(url));

        pdfBytes.SaveAs($"{Guid.NewGuid()}.pdf");
        Console.WriteLine($"Successfully converted {url} to PDF.");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Failed to convert {url} to PDF: {ex.Message}");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

In the above code, we iterate over a set of test URLs and attempt to convert each of them to PDF. If a request fails, the exception will be caught, and an appropriate message will be displayed in the console.

.NET Core Polly (How It Works For Developers): Figure 1 - URL to PDF Output

Conclusion

Polly is a powerful and flexible library for implementing resilience and transient fault handling in .NET Core applications. By combining policies like retry and circuit breaker, developers can build robust and fault-tolerant systems that gracefully handle failures.

In this tutorial, we explored how to use Polly with IronPDF to convert a URL to PDF. We learned how to define and apply Polly policies, including retry and circuit breaker. We also tested our policies with different URLs. We can also do it for converting HTML to PDF.

IronPDF offers a free trial, and licenses start at competitive pricing, allowing you to leverage its capabilities in your projects.

Preguntas Frecuentes

¿Qué es Polly y cómo mejora la resiliencia de .NET Core?

Polly es una biblioteca .NET diseñada para la resiliencia y el manejo de fallos transitorios, especialmente para aplicaciones ASP.NET Core. Mejora la resiliencia proporcionando estrategias como Reintento, Disyuntores, Tiempo de espera, Aislamiento de compartimentos y Respaldo, asegurando sistemas robustos y tolerantes a fallos.

¿Cómo puedo usar Polly para implementar una política de reintento en .NET Core?

En .NET Core, puedes usar Polly para implementar una política de reintento configurándolo para que reintente automáticamente las solicitudes fallidas. Esto se puede hacer estableciendo el número de reintentos y el intervalo de tiempo entre los intentos, permitiendo una gestión efectiva de los fallos transitorios.

¿Cómo previene la Política de Disyuntor fallos en cascada en aplicaciones .NET?

La Política de Disyuntor en Polly previene fallos en cascada monitoreando fallos y abriendo el circuito para bloquear solicitudes cuando se alcanza un umbral de fallos. Esto detiene solicitudes adicionales hasta que el circuito se reinicia, permitiendo que el sistema se recupere antes de aceptar nuevas solicitudes.

¿Qué papel desempeña el Aislamiento de Compartimentos en la gestión del agotamiento de recursos?

El Aislamiento de Compartimentos en Polly limita el número de solicitudes concurrentes a un servicio, previniendo el agotamiento de recursos al controlar los espacios de ejecución. Esta política ayuda a contener fallos y asegura una gestión eficiente de recursos dentro de una aplicación .NET Core.

¿Cómo puede la Política de Tiempo de Espera de Polly mejorar la capacidad de respuesta de mi aplicación?

La Política de Tiempo de Espera de Polly impone un tiempo máximo de ejecución para operaciones, lo que ayuda a gestionar escenarios donde los servicios no responden puntualmente. Al establecer tiempos de espera optimistas o pesimistas, los desarrolladores pueden asegurar que sus aplicaciones permanezcan receptivas.

¿Se puede usar Polly para mejorar la fiabilidad de la conversión de URL a PDF?

Sí, Polly puede mejorar la fiabilidad de la conversión de URL a PDF integrando sus políticas de Reintento y Disyuntor con herramientas de generación de PDF. Esto asegura que los procesos de conversión sean resistentes a fallos transitorios, manteniendo la fiabilidad.

¿Cómo asegura la Política de Respaldo en Polly una degradación elegante del servicio?

Una Política de Respaldo en Polly proporciona respuestas o comportamientos alternativos cuando un servicio falla. Esto ayuda a asegurar que un fallo no detenga toda la aplicación, permitiendo una degradación elegante y operación continua.

¿Cómo se combinan múltiples políticas de Polly en una aplicación .NET?

En una aplicación .NET, se pueden combinar múltiples políticas de Polly usando envolturas de políticas. Esto permite a los desarrolladores ejecutar diferentes estrategias de resiliencia juntas, habilitando un enfoque más integral y flexible para manejar fallos.

¿Cómo maneja la integración de Polly con IronPDF los fallos transitorios en la generación de PDF?

Al integrar Polly con IronPDF, los desarrolladores pueden manejar fallos transitorios durante la generación de PDF a través de políticas como reintento y disyuntor. Esta integración asegura una generación de PDF estable y fiable a pesar de interrupciones ocasionales en el servicio.

¿Cuáles son algunas estrategias comunes de solución de problemas al usar Polly con .NET Core?

Las estrategias comunes de solución de problemas incluyen verificar configuraciones de políticas, como intervalos de reintento y umbrales de disyuntor, y probar políticas con diferentes escenarios para asegurar un manejo adecuado de fallos y la resiliencia del sistema.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más