【问题标题】:Logging Polly wait and retry policy ASP.NET CORE 2.1记录 Polly 等待和重试策略 ASP.NET CORE 2.1
【发布时间】:2019-05-05 08:51:52
【问题描述】:

我需要在 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 上的更好的方法。

【问题讨论】:

标签: c# asp.net-core .net-core asp.net-core-webapi polly


【解决方案1】:

由于您使用的是 ASP.NET core 2.1,请考虑使用 HttpClientFactory。非常适合 polly,具有额外的好处,并且简化了日志记录。

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

【讨论】:

    【解决方案2】:

    使用 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

    【讨论】:

    • 我有一个类似的代码,重试停止工作,因为我得到一个空指针异常,因为 services.GetService>() 在上下文中没有解析。出于安全原因,请使用 SeriLog 静态对象“Log”或至少将日志记录放入 try catch
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-28
    • 2022-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多