微服务设计模式
核心模式
| 模式 | 解决的问题 | 工作方式 |
|---|---|---|
| API 网关 | 客户端需调用多个服务 | 统一入口:路由、认证、限流、聚合 |
| 熔断器 | 级联故障 | N次失败后打开;快速失败;半开探测 |
| Saga | 分布式事务 | 本地事务链 + 补偿事务 |
| CQRS | 读写竞争 | 读模型与写模型分离 |
| 事件溯源 | 审计日志、状态回溯 | 存储事件而非状态,从日志重建状态 |
| Outbox 模式 | DB+消息双写原子性 | 写 DB 的 outbox 表,中继器发布到消息队列 |
| 绞杀者模式 | 单体渐进式迁移 | 新功能走新服务,逐步替换旧代码 |
| Sidecar | 每个 Pod 的横切关注点 | 同部署代理(Envoy)处理可观测性、认证 |
熔断器实现
// 熔断器状态:CLOSED → OPEN → HALF-OPEN → CLOSED
class CircuitBreaker {
constructor(fn, { threshold = 5, timeout = 60000 } = {}) {
this.fn = fn;
this.state = 'CLOSED';
this.failureCount = 0;
this.threshold = threshold;
this.timeout = timeout;
this.nextAttempt = null;
}
async call(...args) {
if (this.state === 'OPEN') {
if (Date.now() < this.nextAttempt) {
throw new Error('熔断器已打开');
}
this.state = 'HALF-OPEN';
}
try {
const result = await this.fn(...args);
this.failureCount = 0;
this.state = 'CLOSED';
return result;
} catch (err) {
this.failureCount++;
if (this.failureCount >= this.threshold || this.state === 'HALF-OPEN') {
this.state = 'OPEN';
this.nextAttempt = Date.now() + this.timeout;
}
throw err;
}
}
}
Saga 模式:编排 vs 协同
// 协同 Saga——各服务监听事件并响应
// 事件流示例:
OrderCreated → PaymentProcessed → StockReserved → OrderConfirmed
↗ PaymentFailed → OrderCancelled
↗ StockFailed → RefundPayment → OrderCancelled
// 编排 Saga——中央编排器指挥各步骤
class OrderSagaOrchestrator {
async execute(orderId) {
try {
await paymentService.charge(orderId);
await inventoryService.reserve(orderId);
await shippingService.schedule(orderId);
await orderService.confirm(orderId);
} catch (err) {
// 按逆序执行补偿操作
await shippingService.cancel(orderId);
await inventoryService.release(orderId);
await paymentService.refund(orderId);
await orderService.cancel(orderId);
}
}
}