本文次要内容为seata的实际篇,理论知识不懂的请参考前文:

我还不懂什么是分布式事务

次要介绍两种最罕用的TCC和AT模式。

环境信息:

mysql:5.7.32

seata-server:1.4.1

SpringCloud:Hoxton.SR10

SpringBoot:2.3.8.RELEASE

注册核心:Eureka

波及服务:

Seata-server

1、在file.conf中批改

mode = "db"

而后配置DB信息:

  ## database store property  db {    datasource = "druid"    ## mysql/oracle/postgresql/h2/oceanbase etc.    dbType = "mysql"    driverClassName = "com.mysql.jdbc.Driver"    url = "jdbc:mysql://127.0.0.1:3306/seata"    user = "root"    password = "123456"    minConn = 5    maxConn = 100    globalTable = "global_table"    branchTable = "branch_table"    lockTable = "lock_table"    queryLimit = 100    maxWait = 5000  }

2、在register.conf

registry {  # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa  type = "eureka"  loadBalance = "RandomLoadBalance"  loadBalanceVirtualNodes = 10  eureka {    serviceUrl = "http://eureka-chengdu:8761/eureka,http://eureka-hangzhou:8762/eureka"    application = "seata-server"    weight = "1"  }

3、客户端批改

这里所指的客户端蕴含所有的资源管理器,蕴含所有须要seata-server治理的服务

在服务启动yml中减少:

seata:  enabled: true  # 事务群组(能够每个利用独立取名,也能够应用雷同的名字)  tx-service-group: my_tx_group  client:    rm-report-success-enable: true    # 异步提交缓存队列长度(默认10000)    rm-async-commit-buffer-limit: 1000    # 一阶段全局提交后果上报TC重试次数(默认1次,倡议大于1)    tm-commit-retry-count:   3    # 一阶段全局回滚后果上报TC重试次数(默认1次,倡议大于1)    tm-rollback-retry-count: 3    support:      # 数据源主动代理开关(默认false敞开)      spring-datasource-autoproxy: false  service:    vgroup-mapping:      # TC 集群(必须与seata-server保持一致)      my_tx_group: seata-server    grouplist:      default: seata-server:8091  registry:    type: eureka    eureka:      serviceUrl: http://eureka-chengdu:8761/eureka/,http://eureka-hangzhou:8762/eureka/

TCC模式

TCC模式实际须要四个服务,除了seata-server外,其余服务调用关系如下:

business服务是全局事务的发起者,须要减少@GlobalTransactional注解

@Override@GlobalTransactionalpublic String processTcc(Map<String, String> params) {    String xid = RootContext.getXID();    System.out.println(("---》》》》xid:" + xid));    uploadFeign.upload(params);    downloadFeign.download(params);    return xid;}

business服务会通过feign近程调用upload和download服务,这两个服务都要申明TCC的三个接口,并通过TwoPhaseBusinessAction注解申明。

upload服务:

@LocalTCCpublic interface TccService {    @TwoPhaseBusinessAction(name = "upload", commitMethod = "commitTcc", rollbackMethod = "cancel")    String upload(@BusinessActionContextParameter(paramName = "params") Map<String, String> params);    boolean commitTcc(BusinessActionContext context);    boolean cancel(BusinessActionContext context);}

具体实现,这里模仿了TCC后果并放到Result中,通过restful接口能够查看,理论业务须要思考防悬挂空回滚问题,例子只是简略形容如何应用TCC模式:

@Slf4j@Servicepublic class TccServiceImpl implements TccService {    @Value("${spring.application.name}")    private String appName;    @PostConstruct    private void initAppName() {        Result.getResult().setAppName(appName);    }    @Override    public String upload(Map<String, String> params) {        String xid = RootContext.getXID();        System.out.println(("---》》》》xid: " + xid));        return "success";    }    @Override    public boolean commitTcc(BusinessActionContext context) {        String xbid = context.getXid();        System.out.println(("---》》》》xid: " + xbid + "提交胜利"));        Result.getResult().setActionResult(context.getXid(), +context.getBranchId(), "Commit", context.getActionContext("params"));        return true;    }    @Override    public boolean cancel(BusinessActionContext context) {        System.out.println(("---》》》》xid: " + context.getXid() + "回滚胜利"));        Result.getResult().setActionResult(context.getXid(), context.getBranchId(), "Rollback", context.getActionContext("params"));        return true;    }}

download服务

download服务也同样须要申明一个TCC接口,实现上在Try阶段模仿每三次调用,,提早30s失败一次场景

@Overridepublic String download(Map<String, String> params) {    String xid = RootContext.getXID();    System.out.println(("---》》》》xid: " + xid));    if (count.incrementAndGet() % 3 == 0) {        try {            TimeUnit.SECONDS.sleep(30);        } catch (InterruptedException e) {            log.warn("InterruptedException", e);        }        throw new RuntimeException("服务异样");    }    return "success";}

测试

1、通过restful接口调用两次,返回全局事务ID

2、查看download和upload服务后果,能够看到后果都是胜利。

upload后果:

3、通过日志查看

seata-server:

business服务日志:

第三次调用

第三次模仿的是download服务失败场景,所以能看到download后果是失败回滚

然而upload服务并没有异样,来看下是否可能和download保障事务的一致性,后果都是回滚呢?

从后果看到两个服务后果是雷同的,从而也看出保障了事务一致性。

从seata-server日志也能看到回滚胜利的信息:

AT模式

AT模式实际须要四个服务,除了seata-server外,其余服务调用关系如下:

模仿电商场景,下订单、减库存,解决胜利后,第三次调用时延时30s抛出异样

业务触发测,也就是全局事务发动服务business服务:

    @Override    @GlobalTransactional(rollbackFor = Exception.class)    public String processAt(String userId, int orderMoney, String commodityCode, int count) throws InterruptedException {        String xid = RootContext.getXID();        System.out.println("---》》》》xid:" + xid);        System.out.println(("------->创立订单开始"));        orderFeign.create(userId, commodityCode, count, orderMoney);        System.out.println(("------->创立订单完结"));        System.out.println(("------->扣减库存开始"));        storageFeign.deduct(commodityCode, count);        System.out.println(("------->扣减库存完结"));        if (visitCount.incrementAndGet() % 3 == 0) {            TimeUnit.SECONDS.sleep(30);            throw new RuntimeException("process failed");        }        return xid;    }

order服务、storage服务

除了配置中减少seata外,与一般的入库服务是一样的

@Servicepublic class OrderDao {    @Autowired    private JdbcTemplate jdbcTemplate;    public boolean createOrder(Order order) {        String sql = "INSERT INTO product_order (user_id,product_id,count,money,status) VALUES('" + order.getUserId() + "', " + order.getProductId() + "," + order.getCount() + ", " + order.getMoney() + ",0);";        return jdbcTemplate.update(sql) > 0;    }}

调用之前:数据:

order数据库为空,

storage数据库中库存字段为100:

调用两次后:

数据库后果:

第三次调用是模仿延时30s后失败场景,也就是书库更新后,解决数据失败,应该从数据库看到数据回滚过程,提早30s也是为了更好的察看后果,也能够用debug形式察看后果

也能够看到

rollback_info中:

30s后从新查问书库能够看到storage库存变回98,order记录缩小为2条,同时undo_log和seata相干表中数据被清空。

从seata-server日志也能看到回滚信息。

华为

同时看下华为的分布式事务解决方案,相比于seata直观的就是多了交互命令行,从下面例子也能够看出seata目前还只能通过数据库查看后果

其余和seata相似提供了TCC和非侵入两种计划

seata-golang

参考容器时代:seata-golang 接入指南

总结

例子中波及的代码已上传到github

https://github.com/stevenniu9...

如果有工夫还是倡议本人敲一遍代码,看他人的货色都会感觉很简略,一看就会

然而当本人实操时就会发现各种奇奇怪怪的异样,一用就废

纸上得来终觉浅,绝知此事要躬行,

比方例子中子pom依赖为什么不须要配置版本、eureka两个怎么互为正本的、seata相干表中具体数据是什么、debug和提早30s是否会对seata有影响

这些问题本人敲一遍会有更深的了解,更何况代码量是如此的少。

最初感觉写的还行,求关注,求点赞,求转发