Polly的用法

要详细了解就去看仓库的英文wiki,上面介绍的很详细,搜到的英文翻译很烂,中文跟英文意思相差很大!

Policy前提AkaHow does the policy mitigate?
Retry
(policy family)
(quickstart ; deep)
许多故障是暂时的,在一段时间后会正常“Maybe it’s just a blip”允许配置自动重试
Circuit-breaker
(policy family)
(quickstart ; deep)
当系统发生严重故障时,快速响应请求失败比让用户等待要好。
避免故障系统过载有助于恢复系统。

Protecting a faulting system from overload can help it recover.
“Stop doing it if it hurts”

“Give that system a break”
当系统错误超过预配置的数量,系统将断路一段时间。
Timeout
(quickstart ; deep)
超出一定时间的等待,想要得到正确的结果是不太可能的。“Don’t wait forever”保证调用者不需要等待超过设置的超时。
Bulkhead Isolation
(quickstart ; deep)
When a process faults, multiple failing calls backing up can easily swamp resource (eg threads/CPU) in a host.

A faulting downstream system can also cause ‘backed-up’ failing calls upstream.

Both risk a faulting process bringing down a wider system.
“One fault shouldn’t sink the whole ship”Constrains the governed actions to a fixed-size resource pool, isolating their potential to affect others.
Cache
(quickstart ; deep)
Some proportion of requests may be similar.“You’ve asked that one before”Provides a response from cache if known.

Stores responses automatically in cache, when first retrieved.
Fallback
(quickstart ; deep)
Things will still fail - plan what you will do when that happens.“Degrade gracefully”Defines an alternative value to be returned (or action to be executed) on failure.
PolicyWrap
(quickstart ; deep)
Different faults require different strategies; resilience means using a combination.“Defence in depth”Allows any of the above policies to be combined flexibly.

请求重试

当发生请求异常或网络错误时, 就重新尝试N次。

请求超时

当系统超过一定时间的等待,我们就几乎可以判断不可能会有成功的结果。
比如平时一个网络请求瞬间就完成了,如果有一次网络请求超过了 30 秒还没完成,我们就知道这次大概率是不会返回成功的结果了。
因此,我们需要设置系统的超时时间,避免系统长时间做无谓的等待。

1
2
3
4
5
// 超时时间不能超过 30 秒,否则就认为是错误的结果,并执行回调。
Policy.Timeout(30, onTimeout: (context, timespan, task) =>
{
// do something
});

请求断路(Circuit-breaker)

断路: 等待一段时间后再继续。

当系统遇到严重问题时,快速回馈失败比让用户/调用者等待要好,限制系统出错的体量,有助于系统恢复。
比如,当我们去调一个第三方的 API,有很长一段时间 API 都没有响应,可能对方服务器瘫痪了。
如果我们的系统还不停地重试,不仅会加重系统的负担,还会可能导致系统其它任务受影响。
所以,当系统出错的次数超过了指定的阈值,就要中断当前线路,等待一段时间后再继续。

1
2
3
// 当系统出现两次异常时,就停下来,等待 1 分钟后再继续。
Policy.Handle<SomeException>()
.CircuitBreaker(2, TimeSpan.FromMinutes(1));

AspNetCore实践使用

1
2
3
4
5
6
7
8
9
10
11
public class SendCloudMailProvider : INoticeProvider
{
private readonly HttpClient _httpClient;
private readonly ILogger _logger;

public SendCloudMailProvider(HttpClient httpClient, ILogger<SendCloudMailProvider> logger)
{
_httpClient = httpClient;
_logger = logger;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using Polly;
using Polly.Extensions.Http;

services.AddHttpClient<INoticeProvider, SendCloudMailProvider>()
.AddPolicyHandler(GetRetryPolicy())
.AddPolicyHandler(GetCircuitBreakerPolicy());

// 重试策略
static IAsyncPolicy<HttpResponseMessage> GetRetryPolicy()
{
return HttpPolicyExtensions
.HandleTransientHttpError()
.OrResult(msg => msg.StatusCode == System.Net.HttpStatusCode.NotFound)
.WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromMilliseconds(500));
}

// 断路策略
static IAsyncPolicy<HttpResponseMessage> GetCircuitBreakerPolicy()
{
return HttpPolicyExtensions
.HandleTransientHttpError()
.CircuitBreakerAsync(5, TimeSpan.FromSeconds(30));
}

Polly的用法
https://pygyme.com/NET开发/polly的用法/
作者
PYGYME
发布于
2020年12月15日
许可协议