Polly 是一种 .NET 弹性和瞬态故障处理库,允许开发人员以流畅和线程安全的方式表达策略,如重试,断路器,超时,隔离隔离和备用,Polly 适用于 .NET 4.0,.NET 4.5 和 .NET Standard 1.1。
安装 Nuget 程序包:
Install-Package Polly
简单使用:
// Execute an action
var policy = Policy
.Handle<Exception>()
.RetryAsync(10, async (exception, retryCount) =>
{
await LogAsync(exception, $"第{retryCount}次重试");
});
await policy.ExecuteAsync(async () => await DoSomething());
//另外一种使用方式:
var tokenResponse = await Policy
.Handle<Exception>()
.OrResult<TokenResponse>(x => x.IsError)
.RetryAsync(5) //如果使用Retry,会报错误:Please use asynchronous-defined policies when calling asynchronous ExecuteAsync (and similar) methods
.ExecuteAsync(async () =>
{
var client = new DiscoveryClient(_appSettings.IssuerUri);
client.Policy.RequireHttps = false;
var disco = await client.GetAsync();
var tokenClient = new TokenClient(disco.TokenEndpoint, clientId, clientSecret);
return await tokenClient.RequestRefreshTokenAsync(refreshToken);
});
参考资料:
|