name: microservices-design description: 微服务设计模式,包括服务网格、事件驱动架构、Saga模式和API网关
微服务设计
服务边界
根据业务能力定义服务,而不是技术层。每个服务拥有其数据存储并暴露清晰的API契约。
order-service/ -> 拥有订单表,发布OrderCreated事件
inventory-service/ -> 拥有库存表,订阅OrderCreated事件
payment-service/ -> 拥有支付表,处理支付流程
notification-service -> 无状态,订阅事件,发送邮件/SMS
事件驱动通信
interface DomainEvent {
eventId: string;
eventType: string;
aggregateId: string;
timestamp: string;
version: number;
payload: Record<string, unknown>;
}
const orderCreatedEvent: DomainEvent = {
eventId: crypto.randomUUID(),
eventType: "order.created",
aggregateId: orderId,
timestamp: new Date().toISOString(),
version: 1,
payload: { customerId, items, totalAmount },
};
await broker.publish("orders", orderCreatedEvent);
async function handleOrderCreated(event: DomainEvent) {
const { items } = event.payload as OrderPayload;
for (const item of items) {
await db.inventory.update({
where: { productId: item.productId },
data: { quantity: { decrement: item.quantity } },
});
}
await markEventProcessed(event.eventId);
}
使用幂等性键(eventId)来安全处理重复交付。
Saga模式(编排)
class OrderSaga {
private steps: SagaStep[] = [
{
name: "reserveInventory",
execute: (ctx) => inventoryService.reserve(ctx.items),
compensate: (ctx) => inventoryService.release(ctx.items),
},
{
name: "processPayment",
execute: (ctx) => paymentService.charge(ctx.customerId, ctx.amount),
compensate: (ctx) => paymentService.refund(ctx.paymentId),
},
{
name: "confirmOrder",
execute: (ctx) => orderService.confirm(ctx.orderId),
compensate: (ctx) => orderService.cancel(ctx.orderId),
},
];
async run(context: SagaContext): Promise<void> {
const completed: SagaStep[] = [];
for (const step of this.steps) {
try {
const result = await step.execute(context);
Object.assign(context, result);
completed.push(step);
} catch (error) {
for (const s of completed.reverse()) {
await s.compensate(context);
}
throw new SagaFailedError(step.name, error);
}
}
}
}
API网关模式
# Kong或类似网关配置
services:
- name: orders
url: http://order-service:3000
routes:
- paths: ["/api/v1/orders"]
methods: [GET, POST]
plugins:
- name: rate-limiting
config:
minute: 100
- name: jwt
- name: correlation-id
- name: users
url: http://user-service:3000
routes:
- paths: ["/api/v1/users"]
plugins:
- name: rate-limiting
config:
minute: 200
健康检查模式
app.get("/health", async (req, res) => {
const checks = {
database: await checkDatabase(),
cache: await checkRedis(),
broker: await checkMessageBroker(),
};
const healthy = Object.values(checks).every(c => c.status === "up");
res.status(healthy ? 200 : 503).json({
status: healthy ? "healthy" : "degraded",
checks,
version: process.env.APP_VERSION,
uptime: process.uptime(),
});
});
反模式
- 在服务间共享数据库(紧耦合)
- 跨多个服务的同步HTTP链(级联故障)
- 构建分布式单体(服务无法独立部署)
- 在服务间调用中缺少断路器
- 未为事件处理器实现幂等性
- 使用分布式事务而非Saga
检查清单
- [ ] 每个服务拥有自己的数据存储
- [ ] 服务通过事件进行异步工作流通信
- [ ] 使用Saga模式进行多服务事务与补偿
- [ ] 断路器防止级联故障
- [ ] API网关处理路由、速率限制和认证
- [ ] 健康检查端点报告依赖状态
- [ ] 事件处理器是幂等的(安全处理重复)
- [ ] 服务可以独立部署和扩展