Implementing the retry pattern

The retry pattern is used to retry the faulted service a number of times in order to get a response. It is widely used in scenarios involving intercommunication between services, where one service is dependent on another service to perform a particular operation. Transient faults occur when services are hosted separately and communicate over the wire, most likely over a HTTP protocol.

The following diagram represents two services: a user registration service that registers and save the user's record in a database, and email service to send a confirmation email to the user so that they can activate their account. Suppose an email service does not respond. This will return some sort of error, and if a retry pattern is implemented, it will retry the request the number of times it has been implemented to do so and will call the email service if it fails:

 

The User Registration Service and the Email Service are ASP.NET Core Web API projects where user registration implements the retry pattern. We will use the Polly framework by adding it as a NuGet package in the user registration service. To add Polly, we can execute the following command from the NuGet package manager console window in Visual Studio:

Install-Package Polly

The Polly framework is based on policies. You can define policies that contain specific configurations related to the pattern you are implementing and then invoke that policy by calling its ExecuteAsync method.

Here is the UserController which contains a POST method that implements a retry pattern to invoke the email service:

[Route("api/[controller]")] 
public class UserController : Controller 
{ 
 
  HttpClient _client; 
  public UserController(HttpClient client) 
  { 
    _client = client; 
  } 
      
  // POST api/values 
  [HttpPost] 
  public void Post([FromBody]User user) 
  { 
             
    //Email service URL 
    string emailService = "http://localhost:80/api/Email"; 
 
    //Serialize user object into JSON string 
    HttpContent content = new StringContent(JsonConvert.SerializeObject(user)); 
 
    //Setting Content-Type to application/json 
    _client.DefaultRequestHeaders 
    .Accept 
    .Add(new MediaTypeWithQualityHeaderValue("application/json")); 
 
 
    int maxRetries = 3; 
 
    //Define Retry policy and set max retries limit and duration between each retry to 3 seconds 
    var retryPolicy = Policy.Handle<HttpRequestException>().WaitAndRetryAsync(
maxRetries, sleepDuration=> TimeSpan.FromSeconds(3)); //Call service and wrap HttpClient PostAsync into retry policy retryPolicy.ExecuteAsync(async () => { var response = _client.PostAsync(emailService, content).Result; response.EnsureSuccessStatusCode(); }); } }

In the preceding code, we have used the HttpClient class to make a RESTful request to the email service API. The HTTP POST method receives a user object that contains the following five properties:

public class User 
{ 
  public string FirstName { get; set; } 
  public string LastName { get; set; } 
  public string EmailAddress { get; set; }  
  public string UserName { get; set; } 
  public string Password { get; set; } 
}  

Since the request will be sent in JSON format, we have to set the Content-Type header value to application/json. Then, we have to define the retry policy to wait and retry the operation every three seconds, with the maximum amount of retries being three. Finally, we call the ExecuteAsync method to invoke the client.PostAsync method so that it calls the email service.

After running the preceding example, if the email service is down or throws an exception, it will be retried three times to try and get the required response.

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

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