
概述 #
微服务架构是云原生应用的核心范式,本文深入探讨其设计原则和技术实现。
架构演进 #
单体架构 #
[用户界面]
↓
[业务逻辑层]
↓
[数据访问层]
↓
[数据库]优点: 开发简单、部署容易、测试方便
缺点: 扩展困难、技术栈单一、故障隔离差
微服务架构 #
[API Gateway]
↓
[用户服务] [订单服务] [支付服务] [库存服务]
↓ ↓ ↓ ↓
[DB] [DB] [DB] [DB]优点: 独立部署、技术灵活、容错性强
缺点: 分布式复杂度、数据一致性、运维成本
核心原则 #
1. 单一职责原则 (SRP) #
每个微服务只做一件事,并把它做好。
# 不好的设计 - 混合太多功能
user-service (用户管理 + 认证 + 授权 + 邮件 + 通知)
# 好的设计 - 职责清晰
auth-service (认证授权)
user-profile-service (用户资料)
notification-service (消息通知)2. 服务拆分粒度 #
| 拆分维度 | 说明 |
|---|---|
| 业务领域 | Bounded Context (限界上下文) |
| 数据边界 | 数据独立性高 |
| 团队规模 | 1-2 个团队维护 |
3. 技术异构性 #
不同微服务可以使用不同技术栈:
services:
user-service:
runtime: Node.js
database: PostgreSQL
payment-service:
runtime: Java
database: MySQL
notification-service:
runtime: Python
database: Redis技术组件 #
API Gateway #
统一入口,处理认证、限流、日志等横切关注点。
# Kong API Gateway 配置
api:
name: api-gateway
hosts:
- api.myapp.com
plugins:
- name: key-auth
- name: rate-limiting
- name: request-transformer服务注册与发现 #
Consul:
# 注册服务
curl -X PUT -d '{"id": "user-service", "name": "user-service", "address": "10.0.0.1", "port": 8080, "checks": [{"http": "http://10.0.0.1:8080/health", "interval": "10s"}]}' http://consul:8500/v1/agent/service/registerEureka (Netflix):
eureka:
client:
registerWithEureka: true
fetchRegistry: true
serviceUrl:
defaultZone: http://eureka-server:8761/eureka/配置中心 #
Apollo:
@Value("${timeout:1000}")
private int timeout;Nacos:
spring:
cloud:
nacos:
config:
server-addr: 127.0.0.1:8848断路器 #
Hystrix:
@HystrixCommand(fallbackMethod = "fallback")
public String getUser(String id) {
return restTemplate.getForObject("http://user-service/users/" + id, String.class);
}
public String fallback(String id) {
return "User not available";
}Resilience4j:
@CircuitBreaker(name = "userService", fallbackMethod = "fallback")
public String getUser(String id) {
return webClient.get().uri("/users/" + id).retrieve().bodyToMono(String.class).block();
}数据一致性 #
2PC (两阶段提交) #
阶段1: 准备阶段
- 协调者询问所有参与者是否可以提交
- 参与者执行事务,写redo日志
阶段2: 提交阶段
- 协调者发送提交命令
- 参与者提交事务,释放资源缺点: 性能差、阻塞、单点故障
Saga 模式 #
序列式:
T1 → T2 → T3 → ... → Tn
补偿: Cn → ... → C3 → C2 → C1并行式:
T1 → T2 → T3
↘ T4
补偿: C3 + C4 → C2 → C1示例 - 订单支付:
@Service
public class OrderService {
@Transactional
public void createOrder(Order order) {
// 1. 创建订单
orderRepository.save(order);
// 2. 扣减库存
inventoryClient.decreaseStock(order.getProductId(), order.getQuantity());
// 3. 扣减余额
accountClient.decreaseBalance(order.getUserId(), order.getAmount());
// 4. 发送消息
消息Service.sendOrderCreated(order);
}
}Event Sourcing #
@Entity
public class Order {
@Id
private String id;
@Aggregate
private AggregateRoot aggregate;
public void apply(OrderCreatedEvent event) {
// 应用事件到聚合
}
}服务网格 #
Istio 架构 #
Data Plane (数据平面)
├── Envoy Proxy (sidecar)
Control Plane (控制平面)
├── Pilot (配置分发)
├── Citadel (安全)
├── Galley (配置验证)
└── Mixer (策略/遥测)基础配置 #
# DestinationRule
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
name: user-service
spec:
host: user-service
trafficPolicy:
connectionPool:
tcp:
maxConnections: 100
http:
h2UpgradePolicy: UPGRADE
http1MaxPendingRequests: 100
http2MaxRequests: 1000
loadBalancer:
simple: ROUND_ROBIN
outlierDetection:
consecutive5xxErrors: 5
interval: 30s
baseEjectionTime: 30s
maxEjectionPercent: 50流量控制 #
# VirtualService
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: user-service
spec:
hosts:
- user-service
http:
- match:
- headers:
X-Client-Type:
exact: mobile
route:
- destination:
host: user-service
subset: v2
retries:
attempts: 3
perTryTimeout: 2s
- route:
- destination:
host: user-service
subset: v1
retries:
attempts: 2
perTryTimeout: 3s
# Subset
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
name: user-service
spec:
host: user-service
subsets:
- name: v1
labels:
version: v1
- name: v2
labels:
version: v2监控告警 #
指标分类 #
| 指标类型 | 示例 |
|---|---|
| Latency | 请求延迟 (ms) |
| Traffic | 请求量 (rps) |
| Errors | 错误数 (err/s) |
| Saturation | 资源利用率 (%) |
SLI/SLO/SLA #
SLI (Service Level Indicator)
- 请求成功率: 99.9%
- 响应时间: P99 < 200ms
SLO (Service Level Objective)
- 未来 30 天,成功率 > 99.9%
SLA (Service Level Agreement)
- 没达到 SLO 赔偿客户关键指标 #
# 请求成功率
rate(http_requests_total{status=~"2.."}[5m])
/
rate(http_requests_total[5m])
# 请求延迟
histogram_quantile(0.99, sum(rate(http_request_duration_seconds_bucket[5m])) by (le))
# 错误率
rate(http_requests_total{status=~"5.."}[5m])最佳实践 #
1. 服务监控 #
- 每个服务独立监控
- 关键指标告警
- 分布式追踪
2. 容错设计 #
- 超时设置
- 重试机制
- 降级策略
- 熔断保护
3. 数据安全 #
- TLS 加密
- 认证授权
- 敏感数据脱敏
4. 持续交付 #
- 自动化测试
- 蓝绿部署
- 金丝雀发布
总结 #
微服务架构需要权衡复杂度和收益,合理使用才能发挥其优势。