0

我有以下政策:

var retryPolicy = Policy.Handle<Exception>(e => (e is HttpRequestException || e.InnerException is HttpRequestException)).WaitAndRetry(
                retryCount: maxRetryCount,
                sleepDurationProvider: attempt => TimeSpan.FromSeconds(Math.Pow(2, attempt)),
                onRetry: (exception, calculatedWaitDuration, retryCount, context) =>
                {
                    Log.Error($"Retry => Count: {retryCount}, Wait duration: {calculatedWaitDuration}, Policy Wrap: {context.PolicyWrapKey}, Policy: {context.PolicyKey}, Endpoint: {context.OperationKey}, Exception: {exception}.");
                });

var circuitBreaker = Policy.Handle<Exception>(e => (e is HttpRequestException || e.InnerException is HttpRequestException)).CircuitBreaker(maxExceptionsBeforeBreaking, TimeSpan.FromSeconds(circuitBreakDurationSeconds), onBreak, onReset);

var sharedBulkhead = Policy.Bulkhead(maxParallelizations, maxQueuingActions, onBulkheadRejected);

var fallbackForCircuitBreaker = Policy<bool>
             .Handle<BrokenCircuitException>()
             .Fallback(
                 fallbackValue: false,
                 onFallback: (b, context) =>
                 {
                     Log.Error($"Operation attempted on broken circuit => Policy Wrap: {context.PolicyWrapKey}, Policy: {context.PolicyKey}, Endpoint: {context.OperationKey}");
                 }
             );

            var fallbackForAnyException = Policy<bool>
                .Handle<Exception>()
                .Fallback(
                    fallbackAction: (context) => { return false; },
                    onFallback: (e, context) =>
                    {
                        Log.Error($"An unexpected error occured => Policy Wrap: {context.PolicyWrapKey}, Policy: {context.PolicyKey}, Endpoint: {context.OperationKey}");
                    }
                );

var resilienceStrategy = Policy.Wrap(retryPolicy, circuitBreaker, sharedBulkhead);
            var policyWrap = fallbackForAnyException.Wrap(fallbackForCircuitBreaker.Wrap(resilienceStrategy));

public bool CallApi(ChangeMapModel changeMessage)
    {
        var httpClient = new HttpClient();
        var endPoint = changeMessage.EndPoint;
        var headers = endPoint.Headers;
        if (headers != null)
        {
            foreach (var header in headers)
            {
                if (header.Contains(':'))
                {
                    var splitHeader = header.Split(':');
                    httpClient.DefaultRequestHeaders.Add(splitHeader[0], splitHeader[1]); 
                }
            } 
        }

        var res = httpClient.PostAsync(endPoint.Uri, null);
        var response = res.Result;
        response.EnsureSuccessStatusCode();
        return true;
    }

我像这样执行策略:

policyWrap.Execute((context) => CallApi(changeMessage), new Context(endPoint));

问题是当在开路上执行操作时,我没有在 CircuitBreaker 回调中受到打击。

我希望通过策略放置 API 调用,要处理的异常类型为HttpRequestException. 政策定义有问题吗?为什么不调用断路器回退?

4

1 回答 1

4

我创建了以下最小、完整、可验证的示例来帮助探索问题:

注:不一定是成品;只是对发布的代码和额外的注释进行了一些小修改,以帮助探索这个问题。

using Polly;
using Polly.CircuitBreaker;
using System;
using System.Net.Http;
using System.Threading.Tasks;

public class Program
{
    public static void Main()
    {
        int maxRetryCount = 6;
        double circuitBreakDurationSeconds = 0.2 /* experiment with effect of shorter or longer here, eg: change to = 1, and the fallbackForCircuitBreaker is correctly invoked */ ;
        int maxExceptionsBeforeBreaking = 4; /* experiment with effect of fewer here, eg change to = 1, and the fallbackForCircuitBreaker is correctly invoked */
        int maxParallelizations = 2;
        int maxQueuingActions = 2;

        var retryPolicy = Policy.Handle<Exception>(e => (e is HttpRequestException || (/*!(e is BrokenCircuitException) &&*/ e.InnerException is HttpRequestException))) // experiment with introducing the extra (!(e is BrokenCircuitException) && ) clause here, if necessary/desired, depending on goal
            .WaitAndRetry(
                retryCount: maxRetryCount,
                sleepDurationProvider: attempt => TimeSpan.FromMilliseconds(50 * Math.Pow(2, attempt)),
                onRetry: (ex, calculatedWaitDuration, retryCount, context) =>
                {
                    Console.WriteLine(String.Format("Retry => Count: {0}, Wait duration: {1}, Policy Wrap: {2}, Policy: {3}, Endpoint: {4}, Exception: {5}", retryCount, calculatedWaitDuration, context.PolicyWrapKey, context.PolicyKey, context.OperationKey, ex.Message));
                });

        var circuitBreaker = Policy.Handle<Exception>(e => (e is HttpRequestException || e.InnerException is HttpRequestException))
            .CircuitBreaker(maxExceptionsBeforeBreaking,
                TimeSpan.FromSeconds(circuitBreakDurationSeconds),
                onBreak: (ex, breakDuration) => {
                    Console.WriteLine(String.Format("Circuit breaking for {0} ms due to {1}", breakDuration.TotalMilliseconds, ex.Message));
                },
                onReset: () => {
                    Console.WriteLine("Circuit closed again.");
                },
                onHalfOpen: () => { Console.WriteLine("Half open."); });

        var sharedBulkhead = Policy.Bulkhead(maxParallelizations, maxQueuingActions);

        var fallbackForCircuitBreaker = Policy<bool>
             .Handle<BrokenCircuitException>()
            /* .OrInner<BrokenCircuitException>() */ // Consider this if necessary.
            /* .Or<Exception>(e => circuitBreaker.State != CircuitState.Closed) */ // This check will also detect the circuit in anything but healthy state, regardless of the final exception thrown.
             .Fallback(
                 fallbackValue: false,
                 onFallback: (b, context) =>
                 {
                     Console.WriteLine(String.Format("Operation attempted on broken circuit => Policy Wrap: {0}, Policy: {1}, Endpoint: {2}", context.PolicyWrapKey, context.PolicyKey, context.OperationKey));
                 }
             );

        var fallbackForAnyException = Policy<bool>
                .Handle<Exception>()
                .Fallback<bool>(
                    fallbackAction: (context) => { return false; },
                    onFallback: (e, context) =>
                    {
                        Console.WriteLine(String.Format("An unexpected error occured => Policy Wrap: {0}, Policy: {1}, Endpoint: {2}, Exception: {3}", context.PolicyWrapKey, context.PolicyKey, context.OperationKey, e.Exception.Message));
                    }
                );

        var resilienceStrategy = Policy.Wrap(retryPolicy, circuitBreaker, sharedBulkhead);
        var policyWrap = fallbackForAnyException.Wrap(fallbackForCircuitBreaker.Wrap(resilienceStrategy));

        bool outcome = policyWrap.Execute((context) => CallApi("http://www.doesnotexistattimeofwriting.com/"), new Context("some endpoint info"));
    }

    public static bool CallApi(string uri)
    {
        using (var httpClient = new HttpClient() { Timeout = TimeSpan.FromSeconds(1) }) // Consider HttpClient lifetimes and disposal; this pattern is for minimum change from original posted code, not a recommendation.
        {
            Task<HttpResponseMessage> res = httpClient.GetAsync(uri);
            var response = res.Result; // Consider async/await rather than blocking on the returned Task.
            response.EnsureSuccessStatusCode();
            return true;
        }
    }
}

fallbackForCircuitBreaker导致不被调用的因素可能不止一个:

  1. circuitBreakDurationSeconds可以设置为比各种尝试和重试之间的等待所花费的总时间短。

如果是这样,电路可能会恢复到半开状态。在半开状态闭合状态下,导致电路断开的异常按原样重新抛出。 BrokenCircuitException仅当(完全)开路阻止尝试调用时才抛出。

因此,如果您的电路在重试耗尽时恢复为半开状态,则抛出回包装回退策略的异常将是HttpRequestException,而不是BrokenCircuitException

  1. .Handle<Exception>(e => (e is HttpRequestException || e.InnerException is HttpRequestException))子句可能会抓住一个CircuitBreakerExceptions 有InnerException is HttpRequestException

ACircuitBreakerException 包含导致电路中断的异常InnerException。因此,过度贪婪/宽松的检查也可能e.InnerException is HttpRequestException导致. 根据您的目标,这可能需要也可能不需要。CircuitBreakerExceptionInnerException is HttpRequestException

我相信由于其构造的特殊方式,原始发布的代码不会发生这种情况。阻塞Task返回的HttpClient.DoSomethingAsync(...)原因已经是一个AggregateException->HttpRequestException,这意味着结果CircuitBreakerException嵌套了HttpRequestException两个深度:

CircuitBreakerException -> AggregateException -> HttpRequestException

因此,这不属于已发布代码中的一次深度检查。但是,请注意aCircuitBreakerException包含导致电路中断的异常InnerException。这可能会导致句柄子句 e.InnerException is HttpRequestException检查不必要的(意外,如果这不是您的目标)重试 a CircuitBreakerException,如果:

(a) 将代码更改为async/ await,这将删除AggregateExceptionand 从而导致嵌套只有一层

(b) 将代码更改为 Polly 的.HandleInner<HttpRequestException>()syntax,它是递归贪婪的,因此会捕获一个 nested-two-deep CircuitBreakerException->AggregateException->HttpRequestException


上述代码中的建议/* commented out */ // with additional explanation建议如何调整发布的代码,以便fallbackForCircuitBreaker按预期调用。


另外两个想法:

  1. 如果可能,请考虑更改为async/await始终。

HttpClient.DoSomethingAsync()通过调用阻塞.Result可能会影响性能,或者如果与其他异步代码混合,可能会导致死锁,并且会带来整个AggregateException痛苦InnerException

  1. HttpClient考虑实例的处置和生命周期。

(故意将这些第 3 点和第 4 点保持简短,如其他地方广泛讨论的那样。)

于 2018-12-19T22:53:31.947 回答