microservices-patterns
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseMicroservices Patterns
微服务模式
Design microservices architectures with service boundaries, event-driven communication, and resilience patterns.
设计具备服务边界、事件驱动通信和弹性模式的微服务架构。
Service Decomposition Strategies
服务拆分策略
By Business Capability
按业务能力拆分
- Organize services around business functions
- Each service owns its domain
- Example: OrderService, PaymentService, InventoryService
- 围绕业务功能组织服务
- 每个服务负责自身领域
- 示例:OrderService, PaymentService, InventoryService
By Subdomain (DDD)
按子域拆分(DDD领域驱动设计)
- Core domain, supporting subdomains
- Bounded contexts map to services
- Clear ownership and responsibility
- 核心域、支持子域
- 限界上下文映射到服务
- 明确的归属与职责
Strangler Fig Pattern
绞杀者模式
- Gradually extract from monolith
- New functionality as microservices
- Proxy routes to old/new systems
- 逐步从单体应用中提取功能
- 新功能以微服务形式实现
- 通过代理路由到新旧系统
Communication Patterns
通信模式
Synchronous (Request/Response)
同步通信(请求/响应)
python
from tenacity import retry, stop_after_attempt, wait_exponential
class ServiceClient:
def __init__(self, base_url: str):
self.base_url = base_url
self.client = httpx.AsyncClient(timeout=5.0)
@retry(stop=stop_after_attempt(3), wait=wait_exponential(min=2, max=10))
async def get(self, path: str, **kwargs):
response = await self.client.get(f"{self.base_url}{path}", **kwargs)
response.raise_for_status()
return response.json()python
from tenacity import retry, stop_after_attempt, wait_exponential
class ServiceClient:
def __init__(self, base_url: str):
self.base_url = base_url
self.client = httpx.AsyncClient(timeout=5.0)
@retry(stop=stop_after_attempt(3), wait=wait_exponential(min=2, max=10))
async def get(self, path: str, **kwargs):
response = await self.client.get(f"{self.base_url}{path}", **kwargs)
response.raise_for_status()
return response.json()Asynchronous (Events/Messages)
异步通信(事件/消息)
python
from aiokafka import AIOKafkaProducer
class EventBus:
async def publish(self, event: DomainEvent):
await self.producer.send_and_wait(
event.event_type,
value=asdict(event),
key=event.aggregate_id.encode()
)python
from aiokafka import AIOKafkaProducer
class EventBus:
async def publish(self, event: DomainEvent):
await self.producer.send_and_wait(
event.event_type,
value=asdict(event),
key=event.aggregate_id.encode()
)Resilience Patterns
弹性模式
Circuit Breaker
断路器模式
python
class CircuitBreaker:
def __init__(self, failure_threshold=5, recovery_timeout=30):
self.failure_threshold = failure_threshold
self.recovery_timeout = recovery_timeout
self.state = CircuitState.CLOSED
async def call(self, func, *args, **kwargs):
if self.state == CircuitState.OPEN:
if self._should_attempt_reset():
self.state = CircuitState.HALF_OPEN
else:
raise CircuitBreakerOpenError()
try:
result = await func(*args, **kwargs)
self._on_success()
return result
except Exception:
self._on_failure()
raisepython
class CircuitBreaker:
def __init__(self, failure_threshold=5, recovery_timeout=30):
self.failure_threshold = failure_threshold
self.recovery_timeout = recovery_timeout
self.state = CircuitState.CLOSED
async def call(self, func, *args, **kwargs):
if self.state == CircuitState.OPEN:
if self._should_attempt_reset():
self.state = CircuitState.HALF_OPEN
else:
raise CircuitBreakerOpenError()
try:
result = await func(*args, **kwargs)
self._on_success()
return result
except Exception:
self._on_failure()
raiseBulkhead Pattern
舱壁模式
- Isolate resources per service
- Limit impact of failures
- Prevent cascade failures
- 按服务隔离资源
- 限制故障影响范围
- 防止级联故障
API Gateway Pattern
API网关模式
python
class APIGateway:
@circuit(failure_threshold=5, recovery_timeout=30)
async def call_service(self, service_url: str, path: str, **kwargs):
response = await self.http_client.request("GET", f"{service_url}{path}", **kwargs)
response.raise_for_status()
return response.json()
async def aggregate(self, order_id: str) -> dict:
# Parallel requests to multiple services
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
)
return {"order": order, "payment": payment, "inventory": inventory}python
class APIGateway:
@circuit(failure_threshold=5, recovery_timeout=30)
async def call_service(self, service_url: str, path: str, **kwargs):
response = await self.http_client.request("GET", f"{service_url}{path}", **kwargs)
response.raise_for_status()
return response.json()
async def aggregate(self, order_id: str) -> dict:
# Parallel requests to multiple services
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
)
return {"order": order, "payment": payment, "inventory": inventory}Data Management
数据管理
Database Per Service
服务专属数据库
- Each service owns its data
- No shared databases
- Loose coupling
- 每个服务拥有自身数据
- 无共享数据库
- 松耦合
Saga Pattern for Distributed Transactions
分布式事务的Saga模式
- See saga-orchestration skill for details
- 详情请参考saga-orchestration skill
Best Practices
最佳实践
- Service Boundaries: Align with business capabilities
- Database Per Service: No shared databases
- API Contracts: Versioned, backward compatible
- Async When Possible: Events over direct calls
- Circuit Breakers: Fail fast on service failures
- Distributed Tracing: Track requests across services
- Health Checks: Liveness and readiness probes
- 服务边界:与业务能力对齐
- 服务专属数据库:不使用共享数据库
- API契约:版本化、向后兼容
- 优先异步通信:使用事件而非直接调用
- 断路器:服务故障时快速失败
- 分布式追踪:跨服务追踪请求
- 健康检查:存活与就绪探针
Common Pitfalls
常见陷阱
- Distributed Monolith: Tightly coupled services
- Chatty Services: Too many inter-service calls
- No Circuit Breakers: Cascade failures
- Synchronous Everything: Tight coupling
- Ignoring Network Failures: Assuming reliable network
- 分布式单体:服务间耦合过紧
- 通信频繁的服务:服务间调用过多
- 未使用断路器:导致级联故障
- 全同步通信:耦合度高
- 忽略网络故障:假设网络可靠