当前位置: 首页 > news >正文

Seata分布式事务实战

Seata分布式事务实战前言Seata是阿里巴巴开源的分布式事务解决方案支持AT、TCC、Saga等多种事务模式。本文将详细介绍Seata的安装配置和AT模式的使用。一、Seata核心概念1.1 架构图┌─────────────────────────────────────────────────────┐ │ Seata Architecture │ │ │ │ ┌──────────────────────────────────────────────┐ │ │ │ TC (Transaction Coordinator) │ │ │ │ Global Session Branch Session Manager │ │ │ └──────────────────────────────────────────────┘ │ │ ▲ ▲ │ │ │ TM │ TM │ │ ┌──────┴──────┐ ┌──────┴──────┐ │ │ │ TM (Transaction Manager) │ │ │ │ │ ┌──────────────────┐ │ │ │ │ │ │ Business Logic │ │ │ │ │ │ └──────────────────┘ │ │ │ │ └────────────────────────┘ │ │ │ │ │ │ ┌──────────────────────────────────────────────┐ │ │ │ RM (Resource Manager) │ │ │ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │ │ │ │ Order DB │ │ Stock DB │ │ Pay DB │ │ │ │ │ └──────────┘ └──────────┘ └──────────┘ │ │ │ └──────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────┘二、Seata Server配置2.1 Docker部署# docker-compose.yml version: 3.8 services: seata: image: seataio/seata-server:1.7.0 container_name: seata-server ports: - 8091:8091 - 7091:7091 environment: - STORE_MODEdb - SEATA_CONFIG_NAMEfile:/root/seata-config/registry - SEATA_IP127.0.0.1 volumes: - ./config:/root/seata-config - seata_data:/root/seata-server/resources depends_on: - mysql mysql: image: mysql:8.0 environment: MYSQL_ROOT_PASSWORD: root_password MYSQL_DATABASE: seata三、AT模式配置3.1 依赖引入dependency groupIdcom.alibaba.cloud/groupId artifactIdspring-cloud-starter-alibaba-seata/artifactId /dependency dependency groupIdio.seata/groupId artifactIdseata-spring-boot-starter/artifactId /dependency3.2 应用配置seata: enabled: true application-id: ${spring.application.name} tx-service-group: my-test-tx-group enable-auto-data-source-proxy: true config: type: nacos nacos: server-addr: ${spring.cloud.nacos.server-addr} namespace: ${spring.cloud.nacos.config.namespace:} group: SEATA_GROUP >Service Slf4j public class OrderServiceImpl implements OrderService { GlobalTransactional(name create-order, rollbackFor Exception.class) Override public OrderDTO createOrder(CreateOrderRequest request) { log.info(Creating order: {}, request); // 1. 创建订单 Order order createLocalOrder(request); // 2. 扣减库存远程调用 boolean stockReduced inventoryClient.reduceStock( request.getProductId(), request.getQuantity() ); if (!stockReduced) { throw new BusinessException(Stock reduction failed); } // 3. 扣减余额远程调用 boolean balanceDeducted accountClient.deductBalance( request.getUserId(), request.getAmount() ); if (!balanceDeducted) { throw new BusinessException(Balance deduction failed); } return orderMapper.toDTO(order); } Transactional public Order createLocalOrder(CreateOrderRequest request) { Order order new Order(); order.setOrderNumber(generateOrderNumber()); order.setUserId(request.getUserId()); order.setProductId(request.getProductId()); order.setQuantity(request.getQuantity()); order.setAmount(request.getAmount()); order.setStatus(OrderStatus.PENDING); return orderRepository.save(order); } }4.2 事务传播Service public class OrderServiceImpl { GlobalTransactional(name outer-transaction) public void outerTransaction() { // 外层事务 createOrder(); // 嵌套事务自动加入外层事务 nestedTransaction(); } Transactional(propagation Propagation.REQUIRES_NEW) public void nestedTransaction() { // 独立事务 doSomething(); } }五、TCC模式配置5.1 TCC接口定义LocalTCC public interface InventoryTccService { TwoPhaseBusinessAction( name prepareInventory, commitMethod commit, rollbackMethod rollback ) boolean prepare( BusinessActionContext actionContext, BusinessActionContextParameter(paramName productId) Long productId, BusinessActionContextParameter(paramName quantity) Integer quantity ); boolean commit(BusinessActionContext actionContext); boolean rollback(BusinessActionContext actionContext); } Service Slf4j public class InventoryTccServiceImpl implements InventoryTccService { Override Transactional public boolean prepare(BusinessActionContext actionContext, Long productId, Integer quantity) { log.info(TCC Prepare: productId{}, quantity{}, productId, quantity); // 预扣减库存 return inventoryRepository.reserveStock(productId, quantity); } Override Transactional public boolean commit(BusinessActionContext actionContext) { log.info(TCC Commit); // 确认扣减 Long productId (Long) actionContext.getActionContext(productId); Integer quantity (Integer) actionContext.getActionContext(quantity); inventoryRepository.confirmStock(productId, quantity); return true; } Override Transactional public boolean rollback(BusinessActionContext actionContext) { log.info(TCC Rollback); // 释放库存 Long productId (Long) actionContext.getActionContext(productId); Integer quantity (Integer) actionContext.getActionContext(quantity); inventoryRepository.releaseStock(productId, quantity); return true; } }5.2 TCC调用Service public class OrderService { Autowired private InventoryTccService inventoryTccService; GlobalTransactional(name create-order-tcc) public void createOrderWithTcc(CreateOrderRequest request) { // 订单创建逻辑... // TCC调用 boolean reserved inventoryTccService.prepare( new BusinessActionContext(), request.getProductId(), request.getQuantity() ); if (!reserved) { throw new BusinessException(Stock reservation failed); } } }六、总结Seata提供了完善的分布式事务解决方案AT模式对业务代码零侵入适合大多数场景TCC模式性能更高适合对性能有较高要求的场景。
http://www.gsyq.cn/news/1370618.html

相关文章:

  • 如何在VSCode中快速配置专业级R语言开发环境:终极实战指南
  • 专业级无损视频封装解决方案:tsMuxer一站式蓝光制作与媒体流处理实战指南
  • 百福黄金回收 - 百福黄金回收
  • 防水套管技术详解:02S404 国标、刚性 / 柔性区别、密封原理 - 品牌优选官
  • 搭建你的第一个AIGC工作流:基于LangChain实现多步链式调用与条件分支
  • 2026年降AI工具长期使用成本横评:按年折算每篇均价完整经济性对比报告
  • 2026年降AI工具支持文件格式横评:PDF与Word处理效果完整对比报告
  • 为什么92%的运维团队还在用grep查日志?DeepSeek日志分析方案上线72小时,MTTD下降86%——附可复用的12个正则增强模板
  • 2026降AI率工具红黑榜:降AIGC软件怎么选?一文讲透
  • 【DeepSeek训练数据准备黄金法则】:20年AI工程师首次公开的5大避坑指南与数据清洗SOP
  • 市面上有哪些是真正高效的降AI率平台(顺利通过高校AIGC审核)
  • 复合材料缺陷检测:纹理分析与多模态融合技术实践
  • 2026权威榜!好用的降AIGC软件全盘点,效率直接拉满!
  • Gemini图像理解能力失效预警清单(含11个高危触发场景):电商主图误判、PPT图表错译、PDF扫描件结构丢失…现在修复还来得及!
  • 量子核方法:原理、实现与在NISQ时代的机器学习应用
  • DeepSeek身份同步延迟突增至8.3s?紧急修复补丁已上线,附3种降级方案(含OpenID Connect兜底脚本)
  • 厦门靠谱婚纱照店大揭秘 - 品牌企业推荐师(官方)
  • 当tail命令穿上GUI外衣:LogExpert如何重新定义Windows日志分析体验
  • 广义随机占优:处理混合尺度数据的鲁棒决策与统计推断框架
  • 2026年京东云OpenClaw/Hermes Agent配置Token Plan部署保姆攻略
  • 零成本解锁Grammarly Premium:智能Cookie采集工具完全指南 [特殊字符]
  • 昇腾CANN hicann:HiCANN 社区基础架构与治理实战
  • 在Node.js后端服务中集成统一的大模型调用层
  • 掌握数字病理分析:QuPath开源工具实战全解析
  • SpringBoot+Vue物流系统源码+论文
  • DeepSeek多租户资源隔离:5大核心机制+3个避坑指南,立即提升SLA至99.99%
  • Arm Compiler 5文档体系解析与使用指南
  • 构建多模型备援策略,使用 Taotoken 提升 AI 服务可用性
  • Warp:AI 开发者的操作系统
  • 机器学习势能加速核量子效应模拟:从路径积分到高效经典MD