微服务设计模式:Saga与CQRS
微服务设计模式:Saga与CQRS
概述
微服务架构需要特定的设计模式。本教程介绍Saga、CQRS和事件溯源模式。
1. Saga模式
// Saga模式:分布式事务管理
// 1. 编排式Saga:中央协调器
// 2. 协同式Saga:事件驱动
// 编排式Saga
@Service
public class OrderSaga {
private final OrderService orderService;
private final PaymentService paymentService;
private final InventoryService inventoryService;
public void createOrder(Order order) {
try {
// 1. 创建订单
orderService.createOrder(order);
// 2. 扣减库存
inventoryService.deductStock(order.getItems());
// 3. 处理支付
paymentService.processPayment(order.getPayment());
} catch (Exception e) {
// 补偿操作
compensate(order);
}
}
private void compensate(Order order) {
// 回滚操作
orderService.cancelOrder(order.getId());
inventoryService.restoreStock(order.getItems());
paymentService.refundPayment(order.getPayment());
}
}
// 协同式Saga
@Component
public class OrderSagaHandler {
@EventListener
public void onOrderCreated(OrderCreatedEvent event) {
// 处理订单创建事件
}
@EventListener
public void onPaymentProcessed(PaymentProcessedEvent event) {
// 处理支付完成事件
}
@EventListener
public void onPaymentFailed(PaymentFailedEvent event) {
// 处理支付失败事件,触发补偿
}
}
2. CQRS模式
// CQRS:命令查询职责分离
// 命令:写操作
// 查询:读操作
// 命令端
@Service
public class OrderCommandService {
private final OrderRepository repository;
@Transactional
public void createOrder(CreateOrderCommand command) {
Order order = new Order(command);
repository.save(order);
// 发布事件
eventPublisher.publish(new OrderCreatedEvent(order));
}
}
// 查询端
@Service
public class OrderQueryService {
private final OrderQueryRepository repository;
public OrderDTO getOrder(Long id) {
return repository.findById(id);
}
public List<OrderDTO> searchOrders(OrderSearchCriteria criteria) {
return repository.search(criteria);
}
}
// 事件
public class OrderCreatedEvent {
private Long orderId;
private LocalDateTime timestamp;
// 构造方法和getter
}
3. 事件溯源
// 事件溯源:将状态变更存储为事件序列
@Service
public class OrderEventSourcing {
private final EventStore eventStore;
public void createOrder(Order order) {
// 存储事件
OrderCreatedEvent event = new OrderCreatedEvent(order);
eventStore.append("order-" + order.getId(), event);
// 应用事件
applyEvent(order, event);
}
public Order getOrder(Long id) {
// 从事件重建状态
List<DomainEvent> events = eventStore.getEvents("order-" + id);
Order order = new Order();
for (DomainEvent event : events) {
applyEvent(order, event);
}
return order;
}
private void applyEvent(Order order, DomainEvent event) {
if (event instanceof OrderCreatedEvent) {
order.apply((OrderCreatedEvent) event);
} else if (event instanceof OrderPaidEvent) {
order.apply((OrderPaidEvent) event);
}
}
}
4. 实际应用示例
分布式事务
@Component
public class DistributedTransactionManager {
private final List<TransactionParticipant> participants;
public void execute(Transaction transaction) {
List<TransactionParticipant> prepared = new ArrayList<>();
try {
// 准备阶段
for (TransactionParticipant participant : participants) {
participant.prepare(transaction);
prepared.add(participant);
}
// 提交阶段
for (TransactionParticipant participant : prepared) {
participant.commit(transaction);
}
} catch (Exception e) {
// 回滚阶段
for (TransactionParticipant participant : prepared) {
participant.rollback(transaction);
}
}
}
}
5. 最佳实践
- Saga模式:用于分布式事务管理
- CQRS模式:分离读写操作,提高性能
- 事件溯源:完整记录状态变更历史
- 最终一致性:接受最终一致性而非强一致性
- 监控和追踪:使用分布式追踪工具
总结
微服务设计模式是构建可靠微服务系统的关键。掌握Saga、CQRS和事件溯源模式,可以设计和实现高质量的微服务架构。