springboot-learning-example集成Seata:分布式事务解决方案

【免费下载链接】springboot-learning-example spring boot 实践学习案例,是 spring boot 初学者及核心技术巩固的最佳实践。 【免费下载链接】springboot-learning-example 项目地址: https://gitcode.com/gh_mirrors/sp/springboot-learning-example

什么是Seata

Seata 是一款开源的分布式事务解决方案,致力于提供高性能和简单易用的分布式事务服务。Seata 将为用户提供了 AT、TCC、SAGA 和 XA 事务模式,为用户打造一站式的分布式解决方案。

Seata的AT模式

前提条件

  • 基于支持本地 ACID 事务的关系型数据库。
  • Java 应用,通过 JDBC 访问数据库。

整体机制

两阶段提交协议的演变:

  • 一阶段:业务数据和回滚日志记录在同一个本地事务中提交,释放本地锁和连接资源。
  • 二阶段:
    • 提交异步化,非常快速地完成。
    • 回滚通过一阶段的回滚日志进行反向补偿。

写隔离

一阶段本地事务提交前,需要确保先拿到全局锁。拿不到全局锁,不能提交本地事务。拿全局锁的尝试被限制在一定范围内,超出范围将放弃,并回滚本地事务,释放本地锁。

读隔离

在数据库本地事务隔离级别读已提交(Read Committed)或以上的基础上,Seata(AT 模式)的默认全局隔离级别是读未提交(Read Uncommitted)。

集成步骤

添加Seata依赖

在项目的pom.xml中添加Seata相关依赖:

<dependency>
    <groupId>io.seata</groupId>
    <artifactId>seata-spring-boot-starter</artifactId>
    <version>最新版本</version>
</dependency>

配置Seata

在application.yml中添加Seata配置:

seata:
  enabled: true
  application-id: ${spring.application.name}
  tx-service-group: my_test_tx_group
  service:
    vgroup-mapping:
      my_test_tx_group: default
    grouplist:
      default: 127.0.0.1:8091
  registry:
    type: file

创建undo_log表

在数据库中创建Seata的回滚日志表:

CREATE TABLE `undo_log` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `branch_id` bigint(20) NOT NULL,
  `xid` varchar(100) NOT NULL,
  `context` varchar(128) NOT NULL,
  `rollback_info` longblob NOT NULL,
  `log_status` int(11) NOT NULL,
  `log_created` datetime NOT NULL,
  `log_modified` datetime NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `ux_undo_log` (`xid`,`branch_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

使用@GlobalTransactional注解

在需要进行分布式事务管理的方法上添加@GlobalTransactional注解:

@Service
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private AccountService accountService;

    @GlobalTransactional
    public void createOrder(Order order) {
        // 创建订单
        orderMapper.insert(order);
        // 扣减账户余额
        accountService.deduct(order.getUserId(), order.getAmount());
    }
}

项目配置文件参考

项目中的配置文件可以参考springboot-properties/src/test/resouorces/application.yml,该文件展示了Spring Boot中属性配置的方式,可以作为Seata配置的参考。

总结

通过以上步骤,我们可以在springboot-learning-example项目中集成Seata,实现分布式事务的管理。Seata提供了多种事务模式,可以根据实际业务场景选择合适的模式。在使用过程中,需要注意配置的正确性和undo_log表的创建。

希望本文能够帮助你在springboot-learning-example项目中成功集成Seata,解决分布式事务问题。如果你有任何问题或建议,欢迎在项目的GitHub仓库中提出。

【免费下载链接】springboot-learning-example spring boot 实践学习案例,是 spring boot 初学者及核心技术巩固的最佳实践。 【免费下载链接】springboot-learning-example 项目地址: https://gitcode.com/gh_mirrors/sp/springboot-learning-example

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐