Polly Circuit Breaker策略和具有ASP.NET Core API的HttpClient

时间:2018-12-31 11:41:19

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

我无法结合HttpClient来设置Polly的CircuitBreaker。

具体来说,以下链接将CircuitBreakerHttpClient用于ASP.NET Core Web API控制器:

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests

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

下面是我想要的

  • 重试策略:如果有暂时性错误,则每个请求重试3次。

  • 断流策略:如果所有请求中都发生短暂错误,则该策略生效。

问题

尽管重试策略正确运行,但断路器策略不起作用。

在发生_httpClient.SendAsync()的5个异常后,CarController仍然接收请求,并且不会暂停30秒(请求由控制器立即处理)。

HandledEventsAllowedBeforeBreaking:5

DurationOfBreakInSeconds:30

我在这里想念东西吗?

ConfigureServices

配置Polly重试和断路器策略,并分隔自定义HttpClient HttpClientService

    public void ConfigureServices(IServiceCollection services)
        {
           services.AddHttpClient();
           services.AddHttpClient<IHttpClientService, HttpClientService>()                                
                        .AddPolicyHandler((service, request) =>
                            HttpPolicyExtensions.HandleTransientHttpError()
                                .WaitAndRetryAsync(3,
                                    retryCount => TimeSpan.FromSeconds(Math.Pow(2, retryCount)),
                onRetry: (outcome, timespan, retryCount, context) =>
                                {
                                    service.GetService<ILog>().Error("Delaying for {delay}ms, then making retry {retry}.",
                                        timespan.TotalMilliseconds, retryCount);
                                }
                            )
)
                        )
                       .AddPolicyHandler((service, request) =>                      
                                HttpPolicyExtensions.HandleTransientHttpError()
                                    //Further external requests are blocked for 30 seconds if five failed attempts occur sequentially.
                                    //Circuit breaker policies are stateful.All calls through this client share the same circuit state.
                                    .CircuitBreakerAsync(5,
                                                 TimeSpan.FromSeconds(30), 
                                                 (result, timeSpan, context)=>
                                                            service.GetService<ILog>().Error("CircuitBreaker onBreak for {delay}ms", timeSpan.TotalMilliseconds),
                                                  context =>
                                                      service.GetService<ILog>().Error("CircuitBreaker onReset")));

         }

CarController

IHttpClientServiceConfigureServices中的Polly策略中指定。 HttpClientService使用HttpClient

断路器无法正常工作:即使在HttpRequestException发生五个瞬时错误(例如_httpClient.SendAsync())之后,CarController仍然可以接收请求,并且不会暂停30秒。

 [ApiVersion("1")]
    [Route("api/v{version:apiVersion}/[controller]")]
    [ApiController]
    public class CarController : ControllerBase
    {
        private readonly ILog _logger;
        private readonly IHttpClientService _httpClientService;
        private readonly IOptions<Config> _config;

        public CarController(ILog logger, IHttpClientService httpClientService, IOptions<Config> config)
        {
            _logger = logger;
            _httpClientService = httpClientService;
            _config = config;
        }

        [HttpPost]
        public async Task<ActionResult> Post()
        {  

            using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
            {
                string body = reader.ReadToEnd();

                    var statusCode = await _httpClientService.PostAsync(
                        "url",
                        new Dictionary<string, string>
                        {
                            {"headerID", "Id"}                           
                        },
                        body);
                    return StatusCode((int)statusCode);               
            }
        }
      }

HttpClientService

似乎HttpClient在请求中不是有状态的。

断路器无法正常工作:即使在HttpRequestException发生五个瞬时错误(例如_httpClient.SendAsync())之后,CarController仍然可以接收请求,并且不会暂停30秒。

 public class HttpClientService
{
    private readonly HttpClient _httpClient;
    public HttpClientService(HttpClient client)
    {
        _httpClient = client;
    }

    public async Task<HttpStatusCode> PostAsync(string url, Dictionary<string, string> headers, string body)
    {
        using (var content = new StringContent(body, Encoding.UTF8, "application/json"))
        {
            foreach (var keyValue in headers)
            {
                content.Headers.Add(keyValue.Key, keyValue.Value);
            }

             var request = new HttpRequestMessage(HttpMethod.Post, url)
                                    {
                                        Content = content
                                    };

            var response = await _httpClient.SendAsync(request);

            response.EnsureSuccessStatusCode();
            return response.StatusCode;
        }

    }

ASP.NET Core API 2.2

更新 更新了SetWaitAndRetryPolicy扩展方法以使用IServiceProvider。

1 个答案:

答案 0 :(得分:0)

断路器策略为stateful to track failure rates across calls,因此需要为long-lived rather than created per request

在发布的代码中使用HttpClientFactory重载的方式:

.AddPolicyHandler((service, request) => HttpPolicyExtensions.HandleTransientHttpError()
    .CircuitBreakerAsync( /* etc */

manufacturing an instance of the circuit-breaker per request,因此断路器永远没有时间建立故障状态。

该重载(和类似内容)为designed for selecting policies dynamically based on characteristics of the request。但实际上,已发布的代码是(编辑:原始已发布的代码)没有使用service, request输入参数,因此您可以删除(service, request) =>部分,并使用重载带有策略实例的HttpClientFactory:

.AddPolicyHandler(HttpPolicyExtensions.HandleTransientHttpError()
    .WaitAndRetryAsync(/* etc */))
.AddPolicyHandler(HttpPolicyExtensions.HandleTransientHttpError()
    .CircuitBreakerAsync(/* etc */))

然后HttpPolicyExtensions.HandleTransientHttpError().CircuitBreakerAsync(/* etc */)返回的那个断路器的长期实例将被配置了HttpClientFactory的HttpClient实例使用。


Sidenote (特别是对于那些想在给定过载下使用断路器的读者):

可以在HttpClientFactory中将断路器与请求驱动的policySelector重载一起使用。仅需要确保通过lambda表达式选择一个实例,而不是每次请求每次都制造一个新实例。例如:

var circuitBreaker = HttpPolicyExtensions.HandleTransientHttpError().CircuitBreakerAsync(/* etc */);
services.AddHttpClient<IHttpClientService, HttpClientService>()                                
    .AddPolicyHandler((service, request) => circuitBreaker); // By way of example technique: more typically with this overload, there is some more complex logic to select different policies for different kinds of request.

编辑以回答评论中的问题:不必将该实例声明为static即可使其长寿。根据上面的代码示例,可以在使用之前立即在Startup.ConfigureServices(...)方法中声明它。 lambda并在HttpClientFactory上配置它会捕获它并使它长寿。

circuitBreaker实例应为shared across calls you want to break in common。如果将断路器连接到通过HttpClientFactory声明的特定HttpClient配置,则稍后通过DI从HttpClientFactory中检索到的,通过该HttpClient配置实例的所有调用将共享circuitBreaker,从而共同中断。

在将断路器与HttpClientFactory一起使用时,这通常意味着您可能希望在每个子系统中对每个要共同调用断路器的子系统在HttpClientFactory上声明一个HttpClient配置(键入或命名)。


侧面注释:断路器的变体也选择了triggers based on consecutive fault count。 (提到以防万一是一个额外的因素;发布的问题是指5个在请求中发生的错误,但不是连续的。)