记录Polly等待和重试策略ASP.NET CORE 2.1

10

我需要记录在ASP.NET CORE 2.1+中通过Polly定义的重试策略。

以下是我的代码,显示了Polly Retry 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网站上介绍的更好的方法来传递ILogger给Polly策略。


如果代码在其他方面都按预期工作,您可以将其发布在 https://codereview.stackexchange.com 上。 - jazb
2个回答

20
使用HttpClientFactory,您可以对预配置的HttpClient应用Polly策略,并在该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


我有一段类似的代码,重试停止工作了,因为我遇到了一个空指针异常,因为services.GetService<ILogger<MyServiceHttpClient>>()在上下文中无法解析。出于安全考虑,只需使用SeriLog静态对象“Log”,或至少将日志记录放在try catch中。 - Adel Tabareh

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接