NEWS

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

[C#] Sử dụng thư viện Polly gửi lại request api khi request bị lỗi hay rớt mạng
Đăng bởi: Thảo Meo - Lượt xem: 1228 09:21:11, 20/01/2024PHẦN MỀM

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 http request khi gặp lỗi

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;
        }
    }
}

pollly_demo_csharp

Thanks for watching!

DOWNLOAD SOURCE

 

Tags: polly c#retry polly c#

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[C#] Sử dụng thư viện Polly gửi lại request api khi request bị lỗi hay rớt mạng
Đăng bởi: Thảo Meo - Lượt xem: 1228 09:21:11, 20/01/2024PHẦN MỀM