微服务架构的难点在于如何正确划分服务边界、处理服务间通信和分布式事务。 Claude Code 能帮你分析业务领域、识别服务边界、生成样板代码。
工作流 1:识别服务边界(领域驱动设计)
Analyze this monolith codebase and suggest microservice boundaries.
Current structure: [粘贴项目目录树]
Business domains described in README: [粘贴业务描述]
Apply Domain-Driven Design principles:
1. Identify bounded contexts (what changes together stays together)
2. Find natural seams where modules rarely talk to each other
3. Identify data ownership (each service owns its data)
4. Flag any shared databases that need to be split
Output:
- Proposed service list with responsibilities
- Service dependency diagram (Mermaid)
- Which tables belong to which service
- Estimated migration complexity (low/medium/high) for each service
工作流 2:生成服务骨架
Generate a microservice skeleton for the "Order Service":
Responsibilities:
- Create and manage orders
- Emit events when order status changes
- Query order history
Tech stack: Python FastAPI, PostgreSQL, Redis, RabbitMQ
Generate:
1. Project structure
2. Domain models (Order, OrderItem, OrderStatus)
3. Repository pattern (async SQLAlchemy)
4. REST API endpoints
5. Event publisher (publish to RabbitMQ on status change)
6. Health check endpoint (/health, /ready)
7. Dockerfile + docker-compose.yml (with dependencies)
8. Environment config with pydantic-settings
工作流 3:API Gateway 设计
Design an API Gateway for these microservices:
- User Service: http://user-service:8001
- Order Service: http://order-service:8002
- Payment Service: http://payment-service:8003
- Notification Service: http://notification-service:8004
Gateway requirements:
1. Route /api/users/* -> User Service
2. Route /api/orders/* -> Order Service
3. JWT authentication (validate token, inject user-id header)
4. Rate limiting (100 req/min per user)
5. Request logging and correlation IDs
6. Circuit breaker (fail fast when service is down)
Use nginx + Lua or Kong or Traefik (recommend the best option).
Generate the full config.
工作流 4:服务间通信
gRPC(同步调用)
Generate gRPC service definition and implementation for
the Order Service calling Payment Service:
1. Write the .proto file:
- PaymentService with methods: Charge, Refund, GetStatus
- Include proper field types and error handling
2. Generate Python server stub (payment-service side)
3. Generate Python client wrapper (order-service side)
- Include retry with exponential backoff
- Include circuit breaker pattern
- Include timeout (default 5s)
4. Show how to test gRPC locally with grpcurl
事件驱动(异步通信)
Implement event-driven communication between Order and Notification service:
Events:
- OrderCreated {orderId, userId, items, total}
- OrderPaid {orderId, paymentId, amount}
- OrderShipped {orderId, trackingNumber, estimatedDelivery}
1. Define event schema (use Pydantic for validation)
2. Publisher (Order Service): publish to RabbitMQ exchange
3. Consumer (Notification Service): subscribe, send email/SMS
4. Dead letter queue for failed processing
5. Event idempotency (don't process same event twice)
Use aio-pika for async RabbitMQ.
工作流 5:分布式事务(Saga 模式)
Implement the Saga pattern for order checkout flow:
Steps:
1. Reserve inventory (Inventory Service)
2. Process payment (Payment Service)
3. Create order record (Order Service)
4. Send confirmation (Notification Service)
If step 2 fails: compensate step 1 (release inventory)
If step 3 fails: compensate steps 1 and 2 (release + refund)
Implement Choreography-based Saga using events:
- Each service listens for events and publishes success/failure events
- Compensation events trigger rollback steps
- Include a Saga state tracker for visibility
Generate the event flow diagram and code for each service's role.
工作流 6:本地开发环境
Generate a docker-compose.yml for local microservices development:
Services:
- api-gateway (nginx)
- user-service (FastAPI, port 8001)
- order-service (FastAPI, port 8002)
- payment-service (FastAPI, port 8003)
- postgres (shared dev DB with separate schemas per service)
- redis
- rabbitmq (with management UI)
- jaeger (distributed tracing UI)
Requirements:
- Hot reload for all Python services (volume mount + watchfiles)
- Shared network for inter-service communication
- Environment variables from .env file
- Health checks with depends_on condition
- Named volumes for data persistence
工作流 7:分布式链路追踪
Add OpenTelemetry distributed tracing to all microservices.
For each FastAPI service:
1. Install opentelemetry-sdk, opentelemetry-instrumentation-fastapi
2. Configure Jaeger exporter
3. Auto-instrument all HTTP requests/responses
4. Add trace context propagation (pass trace-id between services)
5. Add custom spans for critical business operations
6. Add span attributes for debugging (user_id, order_id, etc.)
Show the jaeger UI configuration and how to trace a request
across user-service -> order-service -> payment-service.
CLAUDE.md 微服务项目规范
markdown
## 微服务规范
### 服务设计原则
- 每个服务只负责一个业务域(单一职责)
- 服务之间通过 API 或事件通信,不共享数据库
- 每个服务可以独立部署和扩展
### 通信规范
- 同步调用:gRPC(内部服务)/ REST(外部 API)
- 异步通信:RabbitMQ 事件(状态变更通知)
- 超时:所有同步调用必须设置超时(默认 5s)
- 重试:网络错误最多重试 3 次(指数退避)
### 每个服务必须有
- /health 端点(存活检查)
- /ready 端点(就绪检查)
- 结构化日志(JSON 格式,含 correlation_id)
- OpenTelemetry 追踪
- Dockerfile + docker-compose 片段来源:Anthropic 官方文档 + 微服务架构最佳实践