关于 microservices-design
面向微服务设计者的模式参考,涵盖服务边界、事件通信、Saga、网关与健康检查,并列出常见反模式和实施清单。
主要功能
- 01按业务能力划分服务边界
- 02事件通信与幂等处理
- 03Saga 编排与补偿操作
- 04API 网关和健康检查模式
- 05反模式与实施清单
适用场景
- 01规划服务所有权与数据存储
- 02设计可靠的异步工作流
- 03检查网关、健康与容错方案
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ rohitg00/ awesome-claude-code-toolkit --skill microservices-design安装后在 Claude Code 中输入/microservices-design确认已加载。
详细介绍
微服务设计
服务边界
围绕业务能力定义服务,而非技术分层。每个服务拥有自己的数据存储,并公开清晰的 API 合约。
order-service/ -> owns orders table, publishes OrderCreated events
inventory-service/ -> owns inventory table, subscribes to OrderCreated
payment-service/ -> owns payments table, handles payment processing
notification-service -> stateless, subscribes to events, sends emails/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 or similar gateway config
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 网关负责路由、限流和身份验证
- 健康检查端点会报告依赖项状态
- 事件处理程序具有幂等性(可安全地处理重复事件)
- 服务可以独立部署和扩展
评论
支持 Markdown