EasyCore.Polly
8.0.0
dotnet add package EasyCore.Polly --version 8.0.0
NuGet\Install-Package EasyCore.Polly -Version 8.0.0
<PackageReference Include="EasyCore.Polly" Version="8.0.0" />
<PackageVersion Include="EasyCore.Polly" Version="8.0.0" />
<PackageReference Include="EasyCore.Polly" />
paket add EasyCore.Polly --version 8.0.0
#r "nuget: EasyCore.Polly, 8.0.0"
#:package EasyCore.Polly@8.0.0
#addin nuget:?package=EasyCore.Polly&version=8.0.0
#tool nuget:?package=EasyCore.Polly&version=8.0.0
EasyCore.Polly
一、Polly服务治理
Polly 是一个基于 .NET 的容错与服务治理库,专门用于构建健壮且弹性的应用程序。它提供了重试、超时、熔断、回退(Fallback)、隔离(Bulkhead)等机制,帮助开发者应对网络故障、瞬时错误和服务不可用等问题,提高系统的可靠性和可用性。
Polly 适用于微服务、云原生应用、分布式系统和 API 调用等场景,使开发者能够优雅地处理故障,而无需在代码中编写大量的错误处理逻辑。
Polly 主要提供以下服务治理策略:
1.重试(Retry) 当调用外部服务失败时,Polly 可以自动进行重试,以应对瞬时故障。例如,网络抖动、临时服务不可用等。
2.超时(Timeout) Polly 提供了超时策略,防止某个服务调用长时间无响应,导致请求阻塞。
3.熔断(Circuit Breaker) 熔断器用于防止某个服务长时间不可用时,持续占用资源,导致系统雪崩。它类似于电路保护装置,当错误率达到一定阈值时,短时间拒绝请求,让系统有时间恢复。
4.回退(Fallback) 当所有策略(如重试、熔断)都失败时,可以提供一个降级策略,返回默认值或执行备用逻辑,确保应用程序不会崩溃。
5.隔离或限流(Bulkhead) Polly 允许限制并发请求的数量,防止某个服务的异常影响整个系统。类似于**舱壁(Bulkhead)**设计,确保一个服务故障不会拖垮所有服务。
6.组合策略 在实际应用中,单独使用 Polly 的某一种策略可能无法满足复杂的服务治理需求。例如,我们可能希望同时限制请求时间(超时)、进行失败重试(重试策略)、在多次失败后触发熔断(熔断策略)。为了实现这种组合治理,Polly 提供了 PolicyWrap 机制,允许将多个策略嵌套或组合,形成更加强大的故障恢复方案。
在微服务架构中,Polly、Ocelot 网关、Istio 服务网格都可以用于服务治理,但它们的作用范围、实现方式和适用场景有所不同。Polly可以用作局部策略,作用于单个服务或 API 调用,由开发者在应用代码中显式使用。Polly 代码级容错,适用于单个微服务,在代码级别实现的服务治理,可以灵活地应用于任何 .NET 应用程序(包括 ASP.NET Core、Blazor、WPF 等)。
EasyCore.Polly实现了Polly的全部策略,提供了一个简单的特性,方便用户使用。
二、使用EasyCore.Polly
1.注册EasyCore.Polly
1.1 winform
[STAThread]
static void Main()
{
ApplicationConfiguration.Initialize();
IServiceCollection services = new ServiceCollection();
// Add EasyCorePolly
services.EasyCorePolly();
services.AddSingleton<MainForm>();
var serviceProvider = services.BuildServiceProvider();
var mainForm = serviceProvider.GetRequiredService<MainForm>();
Application.Run(mainForm);
}
1.2 WebApi
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// Add EasyCorePolly
builder.Services.EasyCorePolly();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseAuthorization();
app.MapControllers();
app.Run();
}
}
注册之后即可应用EasyCore.Polly。
2.服务治理策略应用介绍
2.1 重试(Retry)
/// <summary>
/// 重试
/// 重试3次,间隔3秒
/// </summary>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
[PollyConfig(MaxRetry = 3, RetryIntervalSeconds = 3)]
public Task RetryAsync()
{
throw new NotImplementedException();
}
2.2 超时(Timeout)
/// <summary>
/// 超时
/// 超时时间为3秒
/// </summary>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
[PollyConfig(TimeOutSeconds = 3)]
public async Task TimeOutAsync()
{
await Task.Delay(5000);
}
2.3 熔断(Circuit Breaker)
/// <summary>
/// 熔断
/// 熔断前出现允许错误3次。熔断时间10秒
/// </summary>
/// <returns></returns>
[PollyConfig(IsEnableCircuitBreaker = true,
ExceptionsAllowedBeforeBreaking = 3,
SecondsOfBreak = 10)]
public Task CircuitBreakerAsync()
{
throw new NotImplementedException();
}
2.4 回退(Fallback)
/// <summary>
/// 降级
/// 降级前出现允许错误1次。
/// ServiceDegradation 属性指向了服务降级调用的方法名
/// </summary>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
[PollyConfig(IsEnableCircuitBreaker = true,
ExceptionsAllowedBeforeBreaking = 3,
SecondsOfBreak = 10,
ServiceDegradation = "DegradeService")]
public Task FallbackAsync()
{
throw new NotImplementedException();
}
/// <summary>
/// 降级方法
/// </summary>
/// <returns></returns>
public async Task DegradeService()
{
_logger.LogError("Service has been degraded !");
await Task.CompletedTask;
}
2.5 隔离或限流(Bulkhead)
/// <summary>
/// 限流
/// 每秒最多3个请求,队列长度为7
/// </summary>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
[PollyConfig(RateLimit = 3, RateQueuing = 7)]
public async Task RateLimitAsync()
{
await Task.Delay(2000);//模拟耗时操作,加这一行是为了不那么快结束,要不并发都没了
_logger.LogInformation("RateLimitAsync");
}
2.6 组合策略
/// <summary>
/// 组合策略
/// 组合策略:熔断3次50秒熔断+重试3次3秒
/// </summary>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
[PollyConfig(IsEnableCircuitBreaker = true,
ExceptionsAllowedBeforeBreaking = 3,
MaxRetry = 3,
RetryIntervalSeconds = 3,
SecondsOfBreak = 50)]
public Task GroupPollyAsync()
{
throw new NotImplementedException();
}
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net8.0
- Castle.Core.AsyncInterceptor (>= 2.1.0)
- Microsoft.Extensions.Logging (>= 8.0.0)
- Microsoft.Extensions.Logging.Abstractions (>= 8.0.0)
- Microsoft.Extensions.Logging.Console (>= 8.0.0)
- Polly (>= 7.0.1)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.