簡體   English   中英

記錄Polly等待和重試策略ASP.NET CORE 2.1

[英]Logging Polly wait and retry policy ASP.NET CORE 2.1

我需要記錄通過APS.NET CORE 2.1+中的Polly定義的重試策略。

我的代碼如下顯示Polly重試polly並使用HttpClient。

public IServiceProvider ConfigureServices(IServiceCollection services)
        {
          //...

            //https://github.com/App-vNext/Polly/wiki/Polly-and-HttpClientFactory            
            Random jitterer = new Random();
            services.AddHttpClient<SimpleCastClient>()
                //TransientErrors:
                //Network failures(System.Net.Http.HttpRequestException)
                //HTTP 5XX status codes(server errors)
                //HTTP 408 status code(request timeout)
                .AddTransientHttpErrorPolicy(policyBuilder =>
                    //Exponential backoff with Randomisation
                    policyBuilder.WaitAndRetryAsync(10,
                        retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))
                                        + TimeSpan.FromMilliseconds(jitterer.Next(1, 100))
                    ));
}

  [ApiVersion("1")]
    [Route("api/v{version:apiVersion}/[controller]")]
    [ApiController]
    public class MyController : ControllerBase
    {
        ILog _logger;
        private SimpleCastClient _simpleCastClient;

        public MyController(ILog logger, SimpleCastClient simpleCastClient)
        {
            _logger = logger;
            _simpleCastClient = simpleCastClient;
        }

        [HttpPost]
        public async Task Post()
        {           
            await _simpleCastClient.PostAsync();

        }

    }


  public class SimpleCastClient
    {
        private HttpClient _client;

        public SimpleCastClient(HttpClient client)
        {
            _client = client;

        }
        public async Task PostAsync()
        {
            string url = $"http://localhost:1111/api/v1/Mock/";
            using (var content = new StringContent("data", Encoding.UTF8, "application/json"))
            {                
                var response = await _client.PostAsync(url, content);                          
            }
        }
}

我想知道是否有比stevejgordon更好的方法。

由於您使用的是ASP.NET core 2.1,請考慮使用HttpClientFactory。 非常適合與Polly一起使用,並具有其他好處,並且簡化了日志記錄。

https://github.com/App-vNext/Polly/wiki/Polly-and-HttpClientFactory

使用HttpClientFactory,您可以將Polly策略應用於預先配置的HttpClient ,並使用在該Polly策略中在DI上配置的ILogger ,其代碼如下:

services.AddHttpClient<MyServiceHttpClient>(/* etc */)
    .AddPolicyHandler((services, request) => HttpPolicyExtensions.HandleTransientHttpError()
        .WaitAndRetryAsync(new[]
        {
            TimeSpan.FromSeconds(1),
            TimeSpan.FromSeconds(5),
            TimeSpan.FromSeconds(10)
        },             
        onRetry: (outcome, timespan, retryAttempt, context) =>
        {
            services.GetService<ILogger<MyServiceHttpClient>>()
                .LogWarning("Delaying for {delay}ms, then making retry {retry}.", timespan.TotalMilliseconds, retryAttempt);
        }
        ));

參考: https : //github.com/App-vNext/Polly/wiki/Polly-and-HttpClientFactory#configuring-policies-to-use-services-registered-with-di-such-as-iloggert

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM