Polly 断路器不使用 .net 核心 HTTP 客户端维护状态

Polly Circuit breaker not maintaining state with .net core HTTP Client

我已经实施了 polly 重试和断路器策略(已包装)。当调用失败并且电路为上一个调用打开时,下一个调用再次进入重试并再次击中断路器,而不是仅仅抛出 circuitbreakexception。我认为即使使用类型化客户端,HTTP 客户端也会以某种方式重新创建。我无法弄清楚这个问题。这是代码

启动

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        services.AddHttpClient<IIntCall, IntCall>().WrapResilientPolicies();
    }

界面

public interface IIntCall
    {
        Task<bool> DoSomething();
    }

实施:

public class IntCall : IIntCall
    {
    private readonly HttpClient client;

    public IntCall(HttpClient httpClient)
    {
        this.client = httpClient;
    }

    public async Task<bool> DoSomething()
    {
        var response = await client.GetAsync("http://www.onegoogle.com");
        var content = await response.Content.ReadAsStringAsync();
        return false;
    }
}

Polly 实施

public static class CBExtensions
    {
        public static void WrapResilientPolicies(this IHttpClientBuilder builder)
        {
            builder.AddPolicyHandler((service, request) =>
            GetRetryPolicy().WrapAsync(GetCircuitBreakerPolicy()));
        }

    private static IAsyncPolicy<HttpResponseMessage> GetCircuitBreakerPolicy()
    {
        return HttpPolicyExtensions.HandleTransientHttpError()
            .CircuitBreakerAsync(3, TimeSpan.FromSeconds(30), (result, retryAttempt) =>
            {
                Debug.WriteLine("circuit broken");
            },
            () =>
            {
                Debug.WriteLine("circuit closed");
            });
    }

    private static IAsyncPolicy<HttpResponseMessage> GetRetryPolicy()
    {
        return HttpPolicyExtensions.HandleTransientHttpError()
            .Or<Exception>(e => !(e is BrokenCircuitException))
          .WaitAndRetryAsync(3,
              retryAttempt => TimeSpan.FromMilliseconds(500),
              onRetry: (context, attempt) =>
              {
                  Debug.WriteLine("error");
              }
          );
    }
}

我想通了这个问题。因为我正在获取请求详细信息,所以每次调用都会注入策略,因此会更新状态。我将我的代码从

public static void WrapResilientPolicies(this IHttpClientBuilder builder)
        {
            builder.AddPolicyHandler((service, request) =>
            GetRetryPolicy().WrapAsync(GetCircuitBreakerPolicy()));
        }

至此

public static void WrapResilientPolicies(this IHttpClientBuilder builder)
        {
            builder.AddPolicyHandler(
                GetRetryPolicy().WrapAsync(GetCircuitBreakerPolicy()));
        }