一、弹性设计概述
弹性设计是指系统在面对故障和高负载时能够保持可用的能力。
二、重试模式
重试模式用于处理临时故障。
// 使用 Polly 配置重试策略
var retryPolicy = Policy
.Handle<HttpRequestException>()
.WaitAndRetryAsync(3, retryAttempt =>
TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
await retryPolicy.ExecuteAsync(async () => {
await _externalService.MakeRequest();
});
三、熔断模式
熔断模式防止级联故障。
// 使用 Polly 配置熔断策略
var circuitBreakerPolicy = Policy
.Handle<HttpRequestException>()
.CircuitBreakerAsync(
exceptionsAllowedBeforeBreaking: 5,
durationOfBreak: TimeSpan.FromSeconds(30),
onBreak: (ex, breakDuration) => {
_logger.LogWarning("Circuit breaker opened");
},
onReset: () => {
_logger.LogInformation("Circuit breaker reset");
});
四、降级模式
降级模式在服务不可用时提供备选方案。
public async Task<IEnumerable<Product>> GetProducts()
{
try
{
return await _productService.GetProductsAsync();
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to get products, returning fallback");
// 返回缓存的降级数据
return await _cache.GetAsync<IEnumerable<Product>>("fallback_products");
}
}
五、隔离模式
隔离模式限制故障影响范围。
// 使用 SemaphoreSlim 实现并发隔离
public class ResourcePool
{
private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(10);
public async Task<T> ExecuteWithLimit<T>(Func<Task<T>> func)
{
await _semaphore.WaitAsync();
try
{
return await func();
}
finally
{
_semaphore.Release();
}
}
}
六、舱壁模式
舱壁模式将系统划分为独立的隔离区域。
七、超时模式
超时模式防止长时间等待。
// 使用 Polly 配置超时策略
var timeoutPolicy = Policy.TimeoutAsync(TimeSpan.FromSeconds(5));
await timeoutPolicy.ExecuteAsync(async () => {
await _slowService.DoWorkAsync();
});
八、回退模式
回退模式提供备用响应。
// 使用 Polly 配置回退策略
var fallbackPolicy = Policy<IEnumerable<Product>>
.Handle<Exception>()
.FallbackAsync(async (ct) => {
return await GetCachedProducts();
});
var result = await fallbackPolicy.ExecuteAsync(async () => {
return await _productService.GetProductsAsync();
});
九、弹性测试策略
使用混沌工程测试系统的弹性。
十、弹性监控与告警
监控弹性指标并设置告警。