[C#] Use Polly library to resend http request on error

Xin chào các bạn, bài viết hôm nay mình xin giới thiệu các bạn thư viện Polly, dùng để gửi lại request http api khi lỗi request xảy ra: web api lỗi, rớt mạng, timeout...

[C#] Sử dụng thư viện Polly gửi lại request api khi request bị lỗi hay rớt mạng


Ví dụ: Khi các bạn sử dụng http request để lấy dữ liệu tự API Server, nhưng nếu lúc này api đang bị lỗi 503-Service Unavailable.

Thì chúng ta làm sao, nó tiếp tục request thêm n lần: 3,4,5... đảm bảo chúng ta luôn luôn lấy được dữ liệu.

Nếu bình thường, chúng ta tự code thì cũng đơn giản như sau:
private readonly HttpClient _client = new HttpClient(); 

public async Task<HttpResponseMessage> SendRequestWithRetry()
{
    HttpResponseMessage response;
    var sendCount = 0;
    do
    {
        var request = new HttpRequestMessage(HttpMethod.Get, new Uri("https://laptrinhvb.net"));
        response = await _client.SendAsync(request);
        sendCount++;
    }
    while (sendCount < 10 && response.StatusCode == System.Net.HttpStatusCode.ServiceUnavailable);

    return response;
}

Ở source này, các bạn thấy mình sử dụng cấu trúc lệnh do...while để gởi, nếu gởi nó sẽ tiếp tục gởi tiếp 10 lần.

Trong này này mình giới thiệu các bạn thư viện Polly chuyên dụng thể thực hiện công việc này.

Các bạn, cài đặt thư viện Polly từ nuget:
dotnet add package Polly


Ở hình trên các bạn thấy khi nó request lỗi, nó sẽ tiếp tục request tiếp. Source code demo C#, Console:
using Polly;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Retry_requests_poly
{
    internal class Program
    {
        static async Task Main()
        {
           var data =  await MakeHttpRequestWithRetry("http://127.0.0.1:8081/pages/login.html?1152");

            Console.WriteLine("Done!");
            Console.Read();
        }

        static async Task<string> MakeHttpRequestWithRetry(string apiUrl)
        {
            var retryPolicy = Policy
                .Handle<HttpRequestException>()

                  .WaitAndRetryAsync(60, retryAttempt => TimeSpan.FromSeconds(retryAttempt),
                (exception, timeSpan, context) =>
                {
                    Console.WriteLine($"Error: {exception.Message}");
                    Console.WriteLine($"Waiting for internet connection. Retrying in {timeSpan.TotalSeconds} seconds...");
                });

            //.WaitAndRetryForeverAsync(retryAttempt => TimeSpan.FromSeconds(retryAttempt));

            try
            {
               var data = await retryPolicy.ExecuteAsync(async () =>
                {
                    using (HttpClient httpClient = new HttpClient())
                    {
                      
                        HttpResponseMessage response = await httpClient.GetAsync(apiUrl);
                        response.EnsureSuccessStatusCode();                      
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Console.WriteLine("Received data: " + responseBody);
                        return responseBody;
                    }
                });
                return data;
            }
            catch (HttpRequestException ex)
            {
                Console.WriteLine($"Error: {ex.Message}");                
            }
            return null;
        }
    }
}

Chúc các bạn thành công.
DOWNLOAD SOURCE CODE

PASSWORD UNZIP: HUNG.PRO.VN

PASSWORD UNZIP: HUNG.PRO.VN
Chúc Mọi Người Thành Công Với Thủ Thuật Trên.
Nếu mọi người có vướng mắc gì mình chia sẽ trên trang có thể gửi liên hê cho mình tại đây nhé.
Cảm ơn mọi người đã quan tâm.

4 comments:

Ju Hazutora said...

đây là app thông báo api chương web mình hay web khác vậy e? a k hiểu lắm. A chưa tìm hiểu đến vấn đề này nên k rỏ ?

Hạ Tỷ Tỷ said...

e chưa thấy a chia sẽ bài viết nào về chương trình a phát triển nhỉ :D, hay a k muốn chia sẽ những thứ a biết vậy?

Hung Program VN said...

Đây là chương trình thông báo khi trang web bị lỗi a nhé :D

Hung Program VN said...

Hehe, a k có nhiều thời gian để tìm hiểu những thứ bản thân muốn e ạh, nên chỉ bị leech bài bên kia về chia sẽ e nhé. A có thời gian nhiều thì a chia sẽ những thứ vô bổ do bản thân tìm hiểu từ xưa r` e :))

All Right Reserved © 2015 By Hung Pro VN