Microservices patterns

From findscripter/everything-skills · View interactive version

Microservices patterns is an AI agent skill from the GitHub repository findscripter/everything-skills. 当把单体拆分为微服务、设计服务边界与契约、选型服务间通信、处理分布式数据/事务、做韧性与可观测设计时使用;做出含边界划分、通信方式、Saga/熔断等模式与迁移步骤的架构方案;不适用于模块化单体可解决、纯原型或缺乏分布式运维能力的场景;触发词:微服务、服务拆分、Saga、熔断、事件驱动、API 网关。

How to use this skill

Skill file

微服务架构模式

何时使用

不该用的边界:

步骤 / 指令

  1. 划定领域边界与所有权:按业务能力(OrderService / PaymentService / InventoryService)或 DDD 子域/限界上下文切分;每个服务独占一块领域与数据,职责单一、边界清晰。
  2. 定义契约、数据所有权与通信方式:
  1. 设计韧性、可观测与部署策略:为跨服务调用加熔断 + 重试退避 + 超时;分布式事务用 Saga(补偿动作);接入分布式追踪、健康检查(liveness/readiness)、服务注册发现。
  2. 给出迁移步骤与运维护栏:从单体抽取优先用绞杀者模式(Strangler Fig)渐进迁移,新功能先落微服务、用代理在新旧系统间路由;明确回滚、灰度与监控告警边界。

规则:

示例

模式 1:按业务能力拆分 + 事件解耦(Python,节选)

class OrderService:
    async def create_order(self, order_data: dict) -> Order:
        order = Order.create(order_data)
        # 发事件通知其他服务,而非直接调用
        await self.event_bus.publish(
            OrderCreatedEvent(order_id=order.id, customer_id=order.customer_id,
                              items=order.items, total=order.total))
        return order
# PaymentService / InventoryService 各自独立部署、独占数据,监听事件做响应

模式 2:API 网关 + 熔断聚合(节选)

from circuitbreaker import circuit

class APIGateway:
    @circuit(failure_threshold=5, recovery_timeout=30)
    async def call_order_service(self, path, method="GET", **kwargs):
        resp = await self.http_client.request(method, f"{self.order_service_url}{path}", **kwargs)
        resp.raise_for_status()
        return resp.json()

    async def create_order_aggregate(self, order_id: str) -> dict:
        order, payment, inventory = await asyncio.gather(
            self.call_order_service(f"/orders/{order_id}"),
            self.call_payment_service(f"/payments/order/{order_id}"),
            self.call_inventory_service(f"/reservations/order/{order_id}"),
            return_exceptions=True)          # 容忍部分失败,做降级聚合
        result = {"order": order}
        if not isinstance(payment, Exception):   result["payment"] = payment
        if not isinstance(inventory, Exception): result["inventory"] = inventory
        return result

模式 3:同步调用带重试退避(节选)

from tenacity import retry, stop_after_attempt, wait_exponential

@retry(stop=stop_after_attempt(3),
       wait=wait_exponential(multiplier=1, min=2, max=10))
async def get(self, path, **kwargs):
    resp = await self.client.get(f"{self.base_url}{path}", **kwargs)
    resp.raise_for_status()
    return resp.json()

模式 4:Saga 编排(分布式事务 + 补偿)(节选)

class OrderFulfillmentSaga:
    # 每步都配一个补偿动作;任一步失败则按相反顺序补偿已完成步骤
    steps = [
        SagaStep("create_order",      action=create_order,      compensation=cancel_order),
        SagaStep("reserve_inventory", action=reserve_inventory, compensation=release_inventory),
        SagaStep("process_payment",   action=process_payment,   compensation=refund_payment),
        SagaStep("confirm_order",     action=confirm_order,     compensation=cancel_order_confirmation),
    ]

    async def execute(self, order_data):
        completed = []
        try:
            for step in self.steps:
                result = await step.action(context)
                if not result.success:
                    await self.compensate(completed, context)   # 回滚
                    return SagaResult(status=SagaStatus.FAILED, error=result.error)
                completed.append(step)
            return SagaResult(status=SagaStatus.COMPLETED)
        except Exception as e:
            await self.compensate(completed, context)
            return SagaResult(status=SagaStatus.FAILED, error=str(e))

    async def compensate(self, completed, context):
        for step in reversed(completed):     # 反向补偿
            try:
                await step.compensation(context)
            except Exception as e:
                log(f"补偿失败 {step.name}: {e}")   # 补偿失败需告警、可重试

模式 5:熔断器三态(CLOSED → OPEN → HALF_OPEN)

class CircuitState(Enum):
    CLOSED = "closed"        # 正常放行
    OPEN = "open"            # 失败超阈值,快速拒绝
    HALF_OPEN = "half_open"  # 冷却后试探是否恢复
# failure_threshold 次失败 → OPEN;recovery_timeout 后转 HALF_OPEN;
# 连续 success_threshold 次成功 → 回到 CLOSED

注意事项

互见


本条目采编自 sickn33/antigravity-awesome-skills(MIT 许可),经适配重写为中文。

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.