如何为 AsyncCircuitBreakerPolicy 捕获 CircuitState
how to capture CircuitState for AsyncCircuitBreakerPolicy
我有一个 IAsyncPolicy
类型的变量 asyncPolicy
,它有一个或多个策略,包括 AsyncCircuitBreakerPolicy
。现在我想在 API 调用之前获取特定策略 AsyncCircuitBreakerPolicy
,以便我可以提取 Circuit 的状态。
这可能吗?那怎么办下面的代码给出了错误,'IAsyncPolicy' 不包含 'GetPolicy'
的定义
static void Main(string[] args)
{
var asyncPolicy = CreateDefaultRetryPolicy();
var breaker = asyncPolicy.GetPolicy<AsyncCircuitBreakerPolicy>();
var state = breaker.CircuitState;
//Web API call follows with asyncPolicy
Console.ReadKey();
}
public static IAsyncPolicy CreateDefaultRetryPolicy()
{
var retryPolicy = Policy.Handle<BrokenCircuitException>().WaitAndRetryAsync
(
retryCount: 3,
sleepDurationProvider: attempt => TimeSpan.FromSeconds(Math.Pow(2, attempt))
);
var circuitBreaker = Policy.Handle<HttpRequestException>().CircuitBreakerAsync(
exceptionsAllowedBeforeBreaking: 3,
durationOfBreak: TimeSpan.FromSeconds(5000),
onBreak: (exception, timespan, context) => { },
onReset: (context) => { });
return Policy.WrapAsync(retryPolicy, circuitBreaker);
}
.GetPolicy<T>()
是 only for PolicyWraps。从技术上讲,它是 IPolicyWrap
.
上的扩展方法
您可以将 CreateDefaultRetryPolicy()
的 return 类型更改为 AsyncPolicyWrap
public static AsyncPolicyWrap CreateDefaultRetryPolicy()
或者你可以在你调用的地方投射 .GetPolicy<T>()
var breaker = ((IPolicyWrap)asyncPolicy).GetPolicy<AsyncCircuitBreakerPolicy>();
我有一个 IAsyncPolicy
类型的变量 asyncPolicy
,它有一个或多个策略,包括 AsyncCircuitBreakerPolicy
。现在我想在 API 调用之前获取特定策略 AsyncCircuitBreakerPolicy
,以便我可以提取 Circuit 的状态。
这可能吗?那怎么办下面的代码给出了错误,'IAsyncPolicy' 不包含 'GetPolicy'
的定义static void Main(string[] args)
{
var asyncPolicy = CreateDefaultRetryPolicy();
var breaker = asyncPolicy.GetPolicy<AsyncCircuitBreakerPolicy>();
var state = breaker.CircuitState;
//Web API call follows with asyncPolicy
Console.ReadKey();
}
public static IAsyncPolicy CreateDefaultRetryPolicy()
{
var retryPolicy = Policy.Handle<BrokenCircuitException>().WaitAndRetryAsync
(
retryCount: 3,
sleepDurationProvider: attempt => TimeSpan.FromSeconds(Math.Pow(2, attempt))
);
var circuitBreaker = Policy.Handle<HttpRequestException>().CircuitBreakerAsync(
exceptionsAllowedBeforeBreaking: 3,
durationOfBreak: TimeSpan.FromSeconds(5000),
onBreak: (exception, timespan, context) => { },
onReset: (context) => { });
return Policy.WrapAsync(retryPolicy, circuitBreaker);
}
.GetPolicy<T>()
是 only for PolicyWraps。从技术上讲,它是 IPolicyWrap
.
您可以将 CreateDefaultRetryPolicy()
的 return 类型更改为 AsyncPolicyWrap
public static AsyncPolicyWrap CreateDefaultRetryPolicy()
或者你可以在你调用的地方投射 .GetPolicy<T>()
var breaker = ((IPolicyWrap)asyncPolicy).GetPolicy<AsyncCircuitBreakerPolicy>();