Monday, July 1, 2019

Using Polly to improve .NET applications resilience

This is an open source framework for that "allows developers to express transient exception and fault handling policies
such as Retry, Retry Forever, Wait and Retry, or Circuit Breaker in a fluent manner".

A policy basically defines which exceptions to handle, what to do when an exception occurs and you can tell Polly to retry the original method or break and stop the method being called again until a certain time span has passed.
A policy is created using a fluent style interface, so let’s take a look at some simple examples
1. Data base Connection retry policy :- Here is the example to set retry policy b/w c# and mongo db driver.

     public static RetryPolicy DbRetryPolicy()
        {
            return Policy.Handle<System.TimeoutException>()
                 .Or<MongoClientException>()
                 .Or<MongoConnectionException>()
                  .Retry(_maxRetryAttempts, (ex, retryCount) =>
            {
                _logger.Error(Environment.NewLine +
                string.Format("Exception caught on attempt {0} - will retry after delay {1}"
                ,retryCount, _pauseBetweenFailures), ex);  
              });
        }

      public IEnumerable<T> FindAll(TId id)
        {
            return PollyHelper.DbRetryPolicy()
                       .Execute(() =>
                        Collection.FindSync(f => f.Id.Equals(id)).ToEnumerable());
        }

 2. Http retry with policy :- If status code is not success, I have defined retry policy for http Response message.

      public static void ApiRetryPolicy()
        {
                return Policy.Handle<Exception>()
                      .OrResult<HttpResponseMessage>( r=> !r.IsSuccessStatusCode)
                      .Retry(_maxRetryAttempts, (ex, retryCount) =>
            {
                _logger.Error(Environment.NewLine +
                string.Format(" Exception caught on attempt {0} - will retry after delay {1}"
                ,retryCount, _pauseBetweenFailures), ex.Exception);           
            });       
        } 

       public async Task Get()
        {
              return await PollyHelper.ApiRetryPolicy()
                         .ExecuteAsync(() => client.GetAsync("client "));           
        }


No comments:

Post a Comment

Kafka setup in window

Here's a step-by-step guide on how to do it : 1. Prerequisites : Before you begin, make sure you have the following prerequisites inst...