Integrating Polly into ICatalogService

Let's look at how we can incorporate Polly.NET into the cart service. As we saw previously, our use case uses the catalog service to gather detailed information about the items in the user's cart and return them to the client. Furthermore, we will implement CircuitBreakerPolicy on ICatalogClient. CircuitBreakerPolicy follows the failing fast approach, which means that, even if the response of the catalog service doesn't arrive, the runtime continues with the execution of the application.

Before starting, let's add some Polly.NET packages to the Cart.Infrastructure project by using the add package command in the project folder:

dotnet add package Polly

Let's proceed by creating some policies for ICatalogClient by creating a new CatalogServicePolicies static class in Cart.Infrastructure:

using System;
using System.Net;
using System.Net.Http;
using Polly;
using Polly.Extensions.Http;

namespace Cart.Infrastructure.Extensions.Policies
{
public static class CatalogServicePolicies
{
public static IAsyncPolicy<HttpResponseMessage> RetryPolicy()
{
return HttpPolicyExtensions
.HandleTransientHttpError()
.OrResult(msg => msg.StatusCode ==
HttpStatusCode.NotFound)
.WaitAndRetryAsync(3, retryAttempt =>
TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
}

public static IAsyncPolicy<HttpResponseMessage>
CircuitBreakerPolicy()
{
return HttpPolicyExtensions
.HandleTransientHttpError()
.CircuitBreakerAsync(3, TimeSpan.FromMinutes(1));
}
}
}

The preceding code defines two policies:

  • The RetryPolicy static method defines the number of retries to carry out before proceeding with the other policies. It uses the .HandleTransientHttpError and .OrResult methods to detect all the failed conditions that have been returned by the client. Furthermore, it calls the WaitAndRetryAsync method, which restricts the RetryPolicy to a maximum of three retries. With each retry, it increases the sleep duration.
  • The CircuitBreaker static method catches all the error conditions by using .HandleTransientHttpError. It calls the .CircuitBreakerAsync method to define CircuitBreakerPolicyCircuitBreakerPolicy will be triggered after three attempts and will be active for 1 minute.

Now, we can inject the definitions of these policies into our HttpClient instances, as follows:

public static class CatalogServiceExtensions
{
public static IServiceCollection AddCatalogService(this
IServiceCollection services, Uri uri)
{
services.AddScoped<ICatalogService, CatalogService>();

services.AddHttpClient<ICatalogClient, CatalogClient>(client =>
{
client.BaseAddress = uri;
})
.SetHandlerLifetime(TimeSpan.FromMinutes(2))
.AddPolicyHandler(CatalogServicePolicies.RetryPolicy())
.AddPolicyHandler(CatalogServicePolicies.
CircuitBreakerPolicy());


return services;
}
}

As you can see, we are injecting these policies using the AddPolicyHandler method, and we are calling the CatalogServicePolicies static class to get them. It is also essential to notice that, before defining the policies, we use the SetHandlerLifetime method to determine the lifetime of HttpClient. This approach guarantees more resilient communication between the cart service and the catalog service. Furthermore, note that Polly policies can be applied to any third-party dependency call, which means that every time we rely on a third-party service, we need to anticipate this kind of approach in order to gracefully handle errors.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.181.52