Springboot+springcloudAlibaba整合seata1.4

本文详细介绍了如何将Springboot与SpringcloudAlibaba整合Seata1.4来实现全局事务管理。从技术选型、环境准备、文件配置、数据库操作到项目整合和异常处理,每个步骤都清晰阐述,帮助读者理解并实践分布式事务解决方案。
摘要由CSDN通过智能技术生成

Springboot+springcloudAlibaba整合seata1.4

技术选型

框架版本
spring boot2.2.2.RELEASE
spring-cloud-alibaba2.2.3.RELEASE
mybatis-plus3.4.0
nacos2.0.3
seata1.4.0

准备环境

  1. jdk1.8,maven
  2. 链接: nacos
  3. 链接: seata

准备文件

  1. config.txt
  2. nacos-config.sh

准备数据库文件

  1. 创建名称为seata的数据库,执行此sqlmysql.sql
  2. 在需要配置seata服务(服务调用方和被调用方)的数据库中均加入此sqlmysql.sql

修改配置

  1. 将config.txt放在与bin同级的目录
  2. 将nacos-config.sh放在conf目录下面
  3. 修改conf/file.conf
    在这里插入图片描述
    如果数据库为8.0在seata/lib/jdbc中添加相关jar包
    在这里插入图片描述
  4. 修改conf/registry.conf
    在这里插入图片描述
    在这里插入图片描述
  5. 修改config.txt
    在这里插入图片描述

环境搭建

  1. 启动nacos
  2. 在conf目录下点击nacos-config.sh或者右键点击 Git Bash Here(前提有git环境)使用命令 sh nacos-config.sh -h localhost -p 8848 -g SEATA_GROUP -u nacos -w nacos看到以下配置为推送成功
    在这里插入图片描述
  3. 启动seata (window下单击seata/bin/seata-server.bat即可),启动后看nacos的服务列表
    在这里插入图片描述

项目整合

  1. 将registry.conf复制到resources目录下,与application.yml同级
  2. pom.xml添加seata依赖
      <!-- seata-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-seata</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>io.seata</groupId>
                    <artifactId>seata-spring-boot-starter</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.seata</groupId>
            <artifactId>seata-spring-boot-starter</artifactId>
            <version>1.4.0</version>
        </dependency>
  1. application.yml添加seata配置
seata:
  tx-service-group: my_test_tx_group   #这里要特别注意和nacos中配置的要保持一直
  config:
    type: nacos
    nacos:
      #namespace:  #2.2中配置所在命名空间ID,入未配置 默认public空间
      server-addr: 127.0.0.1:8848
      group: SEATA_GROUP
      userName: nacos
      password: nacos
  registry:
    type: nacos
    nacos:
      application: seata-server
      server-addr: 127.0.0.1:8848
      #namespace:    #2.2中配置所在命名空间ID,入未配置 默认public空间
      userName: nacos
      password: nacos
  service:
    vgroup-mapping:
      my_test_tx_group: default    #这里要特别注意和nacos中配置的要保持一直
  1. 启动项目
    这样即为配置成功
    在这里插入图片描述

使用seata做全局事务控制

假设A服务调用B服务,那么就在A服务的方法上面加入,B服务上面不用加

@GlobalTransactional(rollbackFor = Exception.class)

测试

A服务

添加插入方法

    @ApiOperation(value = "添加数据")
    @PostMapping("add")
    @GlobalTransactional(rollbackFor = Exception.class)
    public R add() throws Exception {
        Boolean save = ucenterMemberService.UcenterAdd();
        return R.ok().data("code", save);
    }

Service层(produceService.add())为B服务的新增方法

 @Override
    public Boolean UcenterAdd() {
        UcenterMember ucenterMember = new UcenterMember().setOpenid(RandomUtils.getFourBitRandom()).setMobile(RandomUtils.getFourBitRandom()).setNickname(RandomUtils.getFourBitRandom()).setSex(1);
        boolean save = this.save(ucenterMember);
        R add = produceService.add();
        return save;
    }

运行方法

A服务

2021-09-02 14:31:21.591  INFO 38724 --- [erListUpdater-0] c.netflix.config.ChainedDynamicProperty  : Flipping property: service-produce.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
2021-09-02 14:31:21.701  INFO 38724 --- [nio-8120-exec-7] i.seata.tm.api.DefaultGlobalTransaction  : [10.111.26.200:8091:176702167442030592] commit status: Committed
2021-09-02 14:31:22.301  INFO 38724 --- [h_RMROLE_1_1_16] i.s.c.r.p.c.RmBranchCommitProcessor      : rm client handle branch commit process:xid=10.111.26.200:8091:176702167442030592,branchId=176702169723731969,branchType=AT,resourceId=jdbc:mysql://localhost:3306/service_consumers,applicationData=null
2021-09-02 14:31:22.306  INFO 38724 --- [h_RMROLE_1_1_16] io.seata.rm.AbstractRMHandler            : Branch committing: 10.111.26.200:8091:176702167442030592 176702169723731969 jdbc:mysql://localhost:3306/service_consumers null
2021-09-02 14:31:22.308  INFO 38724 --- [h_RMROLE_1_1_16] io.seata.rm.AbstractRMHandler            : Branch commit result: PhaseTwo_Committed

B服务

2021-09-02 14:31:22.327  INFO 38648 --- [h_RMROLE_1_1_16] i.s.c.r.p.c.RmBranchCommitProcessor      : rm client handle branch commit process:xid=10.111.26.200:8091:176702167442030592,branchId=176702175260213249,branchType=AT,resourceId=jdbc:mysql://localhost:3306/service_produce,applicationData=null
2021-09-02 14:31:22.346  INFO 38648 --- [h_RMROLE_1_1_16] io.seata.rm.AbstractRMHandler            : Branch committing: 10.111.26.200:8091:176702167442030592 176702175260213249 jdbc:mysql://localhost:3306/service_produce null
2021-09-02 14:31:22.348  INFO 38648 --- [h_RMROLE_1_1_16] io.seata.rm.AbstractRMHandler            : Branch commit result: PhaseTwo_Committed

此时给A服务的方法制造异常

    @ApiOperation(value = "添加数据")
    @PostMapping("add")
    @GlobalTransactional(rollbackFor = Exception.class)
    public R add() throws Exception {
        Boolean save = ucenterMemberService.UcenterAdd();
        if (1 == 1) {
            throw new Exception("制造异常");
        }
        return R.ok().data("code", save);
    }

再次启动方法
A服务

 rm handle branch rollback process:xid=10.111.26.200:8091:176703109113610240,branchId=176703109168136193,branchType=AT,resourceId=jdbc:mysql://localhost:3306/service_consumers,applicationData=null
2021-09-02 14:35:04.267  INFO 38724 --- [h_RMROLE_1_2_16] io.seata.rm.AbstractRMHandler            : Branch Rollbacking: 10.111.26.200:8091:176703109113610240 176703109168136193 jdbc:mysql://localhost:3306/service_consumers
2021-09-02 14:35:04.401  INFO 38724 --- [h_RMROLE_1_2_16] i.s.r.d.undo.AbstractUndoLogManager      : xid 10.111.26.200:8091:176703109113610240 branch 176703109168136193, undo_log deleted with GlobalFinished
2021-09-02 14:35:04.402  INFO 38724 --- [h_RMROLE_1_2_16] io.seata.rm.AbstractRMHandler            : Branch Rollbacked result: PhaseTwo_Rollbacked
2021-09-02 14:35:04.480  INFO 38724 --- [io-8120-exec-10] i.seata.tm.api.DefaultGlobalTransaction  : [10.111.26.200:8091:176703109113610240] 

B服务

2021-09-02 14:35:04.411  INFO 38648 --- [h_RMROLE_1_2_16] i.s.c.r.p.c.RmBranchRollbackProcessor    : rm handle branch rollback process:xid=10.111.26.200:8091:176703109113610240,branchId=176703109281382401,branchType=AT,resourceId=jdbc:mysql://localhost:3306/service_produce,applicationData=null
2021-09-02 14:35:04.412  INFO 38648 --- [h_RMROLE_1_2_16] io.seata.rm.AbstractRMHandler            : Branch Rollbacking: 10.111.26.200:8091:176703109113610240 176703109281382401 jdbc:mysql://localhost:3306/service_produce
2021-09-02 14:35:04.465  INFO 38648 --- [h_RMROLE_1_2_16] i.s.r.d.undo.AbstractUndoLogManager      : xid 10.111.26.200:8091:176703109113610240 branch 176703109281382401, undo_log deleted with GlobalFinished
2021-09-02 14:35:04.465  INFO 38648 --- [h_RMROLE_1_2_16] io.seata.rm.AbstractRMHandler            : Branch Rollbacked result: PhaseTwo_Rollbacked

会发现状态为Rollbacked

注意事项

1.如果给B服务手动制造异常而A服务是正常这个时候想数据回滚请勿将异常进行捕捉,否则seata认为你已将异常处理,就不会回滚数据了我之前就是配置了@ControllerAdvice导致数据没有回滚

技术有限,轻喷

Spring Cloud Alibaba学习笔记》其实是阿里的微服务解决方案,是阿里巴巴结合自身微服务实践,开源的微服务全家桶,在Spring Cloud项目中孵化成为Spring Cloud的子项目。第一代的Spring Cloud标准中很多组件已经停更,如:Eureak,zuul等。所以Spring Cloud Alibaba很有可能成为Spring Cloud第二代的标准实现,所以许多组件在业界逐渐开始使用,已有很多成功案例。值得一提的是Spring Cloud Alibaba对Dubbo做了很好的兼容,同时也提供了一些强大的功能,如 Sentinel 流控 ,Seata 分布式事务,Nacos 服务发现与注册等等。 但现在网上学习SpringCloudAlibab的资料要么不全要么很少,完整的就更别说了,所以今天给大家免费分享的正是Alibaba出品的Spring Cloud Alibaba 的学习文档,图文并茂,量身打造,非常适合再学习Spring Cloud Alibaba的朋友观看!下面来看看这份Spring Cloud Alibaba 学习文档吧. Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Spring Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。 为什么使用Spring Boot?很简单,我仅仅只需要非常少的几个配置就可以迅速方便的搭建起来一套 Web 项目或者是构建一个微服务! 本文档主要介绍了Spring Boot 框架快速入门教程以大量示例讲解了 Spring Boot 在各类情境中的应用,让读者可以跟着笔者的思维和代码快速理解并掌握。感兴趣的可以了解一下
Spring Boot + Spring Cloud Alibaba Seata 中配置 TCC 模式,需要进行以下步骤: 1. 引入 Seata TCC 的依赖: ```xml <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-seata</artifactId> <version>2.0.3.RELEASE</version> </dependency> ``` 2. 配置 Seata TCC 的相关参数: ```yaml spring: application: name: demo-service # 应用名称 seata: service: group: my_test_tx_group # 事务分组名称 vgroup-mapping.my_test_tx_group: default # 分组所在的虚拟组 enable-degrade: false # 是否开启降级模式,默认为 false use-jdk-proxy: false # 是否使用 JDK 代理,默认为 false config: type: nacos # 配置中心类型,可以是 file、nacos、apollo、zk nacos: namespace: seata # 命名空间 server-addr: localhost:8848 # Nacos 服务地址 group: SEATA_GROUP # 配置组 username: nacos # 用户名 password: nacos # 密码 file: name: file.conf # 配置文件名 registry: type: nacos # 注册中心类型,可以是 file、nacos、eureka、consul、zk nacos: server-addr: localhost:8848 # Nacos 服务地址 namespace: seata # 命名空间 group: SEATA_GROUP # 注册组 username: nacos # 用户名 password: nacos # 密码 tx-service-group: my_test_tx_group # 事务分组名称 ``` 3. 在需要使用 TCC 模式的方法上使用 @Tcc 注解: ```java @Service public class DemoServiceImpl implements DemoService { @Autowired private AccountService accountService; @Autowired private StorageService storageService; /** * TCC 模式下的分布式事务实现 */ @Override @GlobalTransactional(timeoutMills = 300000, name = "demo-service-tx") public void tccTransaction(String userId, String commodityCode, Integer count) { // 第一步:减少库存 storageService.decrease(commodityCode, count); // 第二步:扣除账户余额 accountService.decrease(userId, count); // 第三步:确认(提交) // do nothing // 第四步:取消(回滚) // do nothing } } ``` 4. 在 Seata 控制台中配置相应的 TCC 事务分组。 以上就是在 Spring Boot + Spring Cloud Alibaba Seata 中配置 TCC 模式的步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值