关于 resilience-patterns
面向开发人员的弹性设计参考技能,介绍重试、熔断、超时、隔舱和降级模式,并提供 TypeScript 与 Java 示例。
主要功能
- 01指数退避重试
- 02熔断器模式
- 03超时处理
- 04隔舱与降级策略选择
- 05resilience4j Java 示例
适用场景
- 01处理临时网络或服务器错误
- 02限制对故障依赖项的重复调用
- 03避免出站请求长时间挂起
- 04为关键路径设计降级响应
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ claude-dev-suite/ claude-dev-suite --skill resilience-patterns安装后在 Claude Code 中输入/resilience-patterns确认已加载。
详细介绍
弹性模式
指数退避重试
async function withRetry<T>(
fn: () => Promise<T>,
maxRetries = 3,
baseDelay = 1000,
): Promise<T> {
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
return await fn();
} catch (error) {
if (attempt === maxRetries) throw error;
if (!isRetryable(error)) throw error;
const delay = baseDelay * Math.pow(2, attempt) + Math.random() * 1000;
await new Promise((r) => setTimeout(r, delay));
}
}
throw new Error('Unreachable');
}
function isRetryable(error: unknown): boolean {
if (error instanceof Error && 'status' in error) {
const status = (error as { status: number }).status;
return status === 429 || status >= 500;
}
return true;
}
熔断器
class CircuitBreaker {
private failures = 0;
private lastFailure = 0;
private state: 'closed' | 'open' | 'half-open' = 'closed';
constructor(
private threshold = 5,
private resetTimeout = 30000,
) {}
async execute<T>(fn: () => Promise<T>, fallback?: () => T): Promise<T> {
if (this.state === 'open') {
if (Date.now() - this.lastFailure > this.resetTimeout) {
this.state = 'half-open';
} else {
if (fallback) return fallback();
throw new Error('Circuit breaker is open');
}
}
try {
const result = await fn();
this.onSuccess();
return result;
} catch (error) {
this.onFailure();
if (fallback) return fallback();
throw error;
}
}
private onSuccess() { this.failures = 0; this.state = 'closed'; }
private onFailure() {
this.failures++;
this.lastFailure = Date.now();
if (this.failures >= this.threshold) this.state = 'open';
}
}
// Usage
const breaker = new CircuitBreaker(5, 30000);
const result = await breaker.execute(
() => externalApi.call(),
() => cachedResult, // fallback
);
resilience4j(Java/Spring)
@CircuitBreaker(name = "paymentService", fallbackMethod = "paymentFallback")
@Retry(name = "paymentService")
@TimeLimiter(name = "paymentService")
public CompletableFuture<Payment> processPayment(Order order) {
return CompletableFuture.supplyAsync(() -> paymentClient.charge(order));
}
public CompletableFuture<Payment> paymentFallback(Order order, Throwable t) {
return CompletableFuture.completedFuture(Payment.pending(order.getId()));
}
# application.yml
resilience4j:
circuitbreaker:
instances:
paymentService:
slidingWindowSize: 10
failureRateThreshold: 50
waitDurationInOpenState: 30s
retry:
instances:
paymentService:
maxAttempts: 3
waitDuration: 1s
exponentialBackoffMultiplier: 2
超时模式
async function withTimeout<T>(fn: () => Promise<T>, ms: number): Promise<T> {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), ms);
try {
return await fn();
} finally {
clearTimeout(timer);
}
}
模式选择
| 模式 | 适用场景 |
|---|---|
| 重试 | 瞬时故障(网络、5xx、429) |
| 熔断器 | 对同一依赖项反复发生故障 |
| 超时 | 防止连接挂起 |
| 隔舱 | 隔离各依赖项的资源池 |
| 回退 | 服务降级但仍可用 |
反模式
| 反模式 | 修正方法 |
|---|---|
| 重试非幂等操作 | 只重试幂等请求(GET、使用相同密钥的 PUT) |
| 重试延迟未添加抖动 | 添加随机抖动,防止惊群效应 |
| 每个请求单独使用熔断器(而非每个服务) | 对发往同一服务的请求共享熔断器实例 |
| 熔断器开启时没有回退方案 | 提供缓存或降级响应 |
| 重试 400 错误 | 只重试瞬时错误(429、5xx、网络错误) |
生产环境检查清单
- 使用指数退避并添加抖动进行重试
- 为所有外部服务调用启用熔断器
- 为所有出站请求设置超时
- 为关键路径提供回退响应
- 健康检查端点
- 监控:熔断器状态、重试次数
评论
支持 Markdown