(五)Spring Cloud Alibaba 2023.x:Seata 分布式事务配置与实现
目录前言准备安装seata下载seata配置seata数据库创建undo_log表seata配置文件启动seata服务项目集成引入seata依赖yml文件配置seata模拟下单生产者提供扣减库存消费者进行下单模拟下单前言在微服务架构中分布式事务是确保多个服务之间数据一致性和完整性的关键。随着微服务的拆分传统的单体事务无法满足跨服务的事务管理需求这时分布式事务变得尤为重要。Seata作为一款轻量级、高性能的分布式事务解决方案通过提供全局事务管理、自动回滚等功能帮助开发者轻松处理分布式系统中的事务问题避免了数据不一致和服务失败的风险。准备jdk17maven3.9.4idea2023spring cloud: 2023.0.1.0spring cloud alibaba: 2023.0.1源码获取GitHub - /spring-cloud-alibaba-base-demo: 基于spring cloud alibaba生态快速构建微服务脚手架安装seata分布式事务seata是一个单独的服务通过这个服务来控制管理业务中的事物所以我们首先的安装配置该seata服务下载seatagithub下载地址https://github.com/apache/incubator-seata/releases百度云地址百度网盘 请输入提取码 提取码: 92h6本篇seata版本为1.8尽量保持一致。seata下载到本地后完整目录如下配置seata数据库进入本地seata项目的db文件夹中在mysql数据库中创建一个seata数据库这里博主使用的是mysql数据库所以选择mysql.sql执行创建了4个表global_table记录全局事务的状态信息。主要用于保存全局事务的唯一标识XID和当前执行状态branch_table记录分支事务的信息。用于关联全局事务中的各个参与分支事务追踪分支的执行状态。lock_table保存全局锁信息。用于防止并发操作对数据造成冲突实现事务数据的锁定。distributed_lock分布式锁表。用于在 Seata 中协调全局的分布式锁防止资源竞争。创建undo_log表在业务数据库中创建undo_log表CREATE TABLE undo_log ( branch_id bigint(20) NOT NULL COMMENT branch transaction id, xid varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT global transaction id, context varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT undo_log context,such as serialization, rollback_info longblob NOT NULL COMMENT rollback info, log_status int(11) NOT NULL COMMENT 0:normal status,1:defense status, log_created datetime(6) NOT NULL COMMENT create datetime, log_modified datetime(6) NOT NULL COMMENT modify datetime, UNIQUE INDEX ux_undo_log(xid, branch_id) USING BTREE, INDEX ix_log_created(log_created) USING BTREE ) ENGINE InnoDB CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci COMMENT AT transaction mode undo table ROW_FORMAT Dynamic;Seata 使用AT 模式自动提交模式时undo_log表会存储业务操作前的镜像数据用于在事务失败时回滚数据到操作前的状态。Seata 在事务完成后(无论是提交还是回滚),会自动清理undo_log数据确保表的干净与高效运行。详细了解seata模式Seata AT 模式 | Apache Seataseata配置文件进入本地的seata项目的config文件中对application.yml文件内容进行修改,下面展示主要的核心配置修改seata: service: vgroup-mapping: dubbo_tx_group: default # 映射 dubbo_tx_group 到 default 服务组 tx-service-group: dubbo_tx_group # 事务服务组名称 config: # support: nacos, consul, apollo, zk, etcd3 type: file # 配置文件类型可以选择 nacos, apollo 等 file: name: file.conf # 使用 application.yml 作为配置文件 registry: # support: nacos, eureka, redis, zk, consul, etcd3, sofa type: nacos # 注册中心类型根据实际情况选择比如 nacos、eureka、zk 等 nacos: server-addr: 127.0.0.1:8848 # Nacos 注册中心地址示例 namespace: # Nacos 的命名空间默认空即可 group: SEATA_GROUP # Seata 在 Nacos 中的分组名 username: nacos # 如果 Nacos 需要登录验证请填入用户名 password: store: # support: file 、 db 、 redis 、 raft mode: db # 使用数据库存储模式也可以选择 file 或 redis db: datasource: druid # 数据源类型可以使用 druid、hikari 等 db-type: mysql # 数据库类型mysql、oracle、postgresql、mariadb 等 driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/seata?useUnicodetruecharacterEncodingutf-8useSSLfalse user: root password: min-conn: 5 max-conn: 30 global-table: global_table branch-table: branch_table lock-table: lock_table query-limit: 100 max-wait: 5000主要配置说明tx-service-group事务组名称设置名称自定义。config: 配置中心可设置适配多个配置中心组件。本篇没有使用配置中心组件选择的是本地文件所以设置的是file。registry注册中心配置seata作为一个服务提供者也需要将服务注册到注册中心管理。这里选择nacos作为注册中心在自己的nacos服务中创建命名空间并在文件中进行替换配置。store 数据存储中心用于存储服务中的全局事务相关数据。这里选择使用的mysql作为存储中心替换自己的数据库配置即可。启动seata服务进入本地seata项目中bin文件夹中window用户双击seata-server.bat启动看到控制台打印上面的地址就表示启动成功了8091 : 表示seata服务的端口7091表示seata控制台的端口访问http://127.0.0.1:7091默认账号密码seata查看seata服务在nacos注册中心也注册成功项目集成根据前面4篇的博文目前我们已经创建了三个微服务引入seata依赖在消费者以及生产者服务都需要引入seata依赖!--分布式事务组件 seata-- dependency groupIdcom.alibaba.cloud/groupId artifactIdspring-cloud-starter-alibaba-seata/artifactId /dependencyyml文件配置seata消费者以及生产者服务的yml文件中都需要配置seata: server: address: 127.0.0.1:8091 tm: default-transaction-manager-type: AT # 默认使用 AT 模式 default-timeout: 30000 # 设置全局事务超时 application-id: ${spring.application.name} # 这里是应用的唯一标识可以根据你的服务名称设置 tx-service-group: dubbo_tx_group # 事务分组名称确保每个 seata 服务的 tx-service-group 一致 registry: type: nacos # 注册中心类型如 nacos若使用其他注册中心需要调整 nacos: server-addr: 127.0.0.1:8848 # Nacos 地址和端口 namespace: group: SEATA_GROUP username: nacos # 如果 Nacos 需要认证 password: config: type: nacos nacos: server-addr: 127.0.0.1:8848 # Nacos 地址和端口 namespace: group: SEATA_GROUP username: nacos # 如果 Nacos 需要认证 password: />注意该文件后缀必须是properties不能是yml官方要求。# 事务组名称 service.vgroupMapping.dubbo_tx_groupdefault service.enableDegradefalse service.disableGlobalTransactionfalse # 事务日志保留时间 server.undo.logSaveDays7 server.undo.logDeletePeriod86400000注意service.vgroupMapping.dubbo_tx_group 这段一定要写对不然项目会一直报错提示找不到该配置。其中后面的dubbo_tx_group必须是自己前面配置 seata文件中tx-service-group属性的值模拟下单数据库相关集成于配置本篇不在概述没有自己项目的可以使用本文开头提供的项目地址进行下载查看使用生产者提供扣减库存RestController public class DemoController { Autowired private SeataProductMapper seataProductMapper; GetMapping(value /test/seata/deInventory) void deInventorySeata(RequestParam(num) Integer num, RequestParam(productId) Integer productId) { seataProductMapper.deInventory(num, productId); } } Mapper public interface SeataProductMapper { Update(UPDATE xf_product SET num num - #{num} WHERE id #{productId}) void deInventory(Param(num) Integer num, Param(productId) Integer productId); }消费者进行下单模拟创建订单Mapper public interface SeataOrderMapper { Insert(INSERT INTO xf_order (user_id, product_id) values (#{userId}, #{productId})) void createOrder(Param(userId) Integer userId, Param(productId) Integer productId); }使用**GlobalTransactional** 实现分布式事务Service public class SeataService { Autowired private FeignService feignService; Autowired private SeataOrderMapper seataOrderMapper; GlobalTransactional(name seata-order, rollbackFor Exception.class) public String placeOrderSeata() { // 调用扣减库存的方法 feignService.deInventorySeata(1, 1); // 调用创建订单的方法 seataOrderMapper.createOrder(1, 1); // throw new RuntimeException(测试回滚); return 下单成功; }定义下单接口RestController public class FeignController { Autowired private SeataService seataService; /** * 使用分布式事务 seata 远程调用Feign * return */ GetMapping(value /seataOrFeignOrSentinel) public String seataOrder() { return seataService.placeOrderSeata(); } }模拟下单启动全部服务并请求下单接口在方法最后debug查看业务数据库undo_log中的数据存在2条操作记录查看seata数据库的全局事务表存在一条全局事务数据查看seata控制台统一正常展示了事务数据放开dedug重新查看相关表数据会发现数据已经清空。也可模拟异常情况查看相关业务表数据是否回滚来验证。注本文使用的是seata的AT模式业务相关表必须在一个库中如果涉及到多个库操作分布式事务考虑使用其他模式实现。至此spring cloud alibaba 微服务集成seata分布式事务完成了
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2412639.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!