我有以下政策:
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
处理异常类型。策略定义有问题吗?为什么不调用断路器后备?
答案 0 :(得分:2)
我创建了以下minimum, complete, verifiable example来帮助探讨问题:
注意:不一定是成品;
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
不被调用:
circuitBreakDurationSeconds
设置为短于重试之间的各种尝试和等待所花费的总时间。 如果是这样,电路可能会恢复到半开状态。在half-open state或closed state中,按原样重新引发导致电路断开的异常。 BrokenCircuitException
仅在(完全)断路阻止呼叫尝试时抛出。
因此,如果在重试耗尽之前电路已恢复为半开状态,则返回到包装回退策略的异常将是HttpRequestException
,而不是BrokenCircuitException
。
.Handle<Exception>(e => (e is HttpRequestException || e.InnerException is HttpRequestException))
子句可能捕获CircuitBreakerException
个具有InnerException is HttpRequestException
的子句 一个CircuitBreakerException
contains the exception which caused the circuit to break as its InnerException
。因此,对e.InnerException is HttpRequestException
的过度贪婪/较宽松的检查也可能会捕获到CircuitBreakerException
具有InnerException is HttpRequestException
的情况。这可能取决于您的目标,也可能不是。
我相信对于原始发布的代码,由于其特殊的构造方式,这种情况不会发生。阻塞Task
返回的HttpClient.DoSomethingAsync(...)
会导致AggregateException->HttpRequestException
,这意味着生成的CircuitBreakerException
嵌套了两个深的HttpRequestException
:
CircuitBreakerException -> AggregateException -> HttpRequestException
因此,这不属于所发布代码中的一个深度检查。但是,请注意,CircuitBreakerException
包含一个异常,该异常导致电路以其InnerException
的形式断开。这可能导致handle子句仅检查 e.InnerException is HttpRequestException
到不必要地(如果不是您的目标,则出乎意料)重试CircuitBreakerException
,如果有:
(a)将代码更改为async
/ await
,这将删除AggregateException
,因此导致嵌套仅深一层
(b)将该代码更改为Polly的.HandleInner<HttpRequestException>()
syntax,这是递归贪婪的,因此将捕获嵌套的两个深度的CircuitBreakerException->AggregateException->HttpRequestException
。
以上代码中的建议/* commented out */ // with additional explanation
建议如何调整所发布的代码,以使fallbackForCircuitBreaker
能够按预期调用。
另外两个想法:
async
/ await
。通过调用HttpClient.DoSomethingAsync()
来阻塞.Result
可能会影响性能,或者如果与其他异步代码混合使用则可能导致死锁,并且会带来整个AggregateException
-with-InnerException
痛苦。
HttpClient
实例的处置和生存期。(保留了第3点和第4点,这在其他地方都得到了广泛讨论。)