Seata 是什么
Seata 是一款开源的分布式事务解决方案,致力于提供高性能和简单易用的分布式事务服务
分布式事务处理过程的一ID+三个组件模型
- Transaction ID XID:全局唯一的事务ID
- 3组件概念
- Transaction Coordinator(TC)–事务协调者:维护全局和分支事务的状态,驱动全局事务提交或回滚。
- Transaction Manager(TM)–事务管理器:定义全局事务的范围:开始全局事务、提交或回滚全局事务。
- Resource Manager(RM)–资源管理器:管理分支事务处理的资源,与TC交谈以注册分支事务和报告分支事务的状态,并驱动分支事务提交或回滚。
处理过程
- TM向TC申请开启一个全局事务,全局事务创建成功并生成一个全局唯一的XID;
- XID在微服务调用链的上下文中传播;
- RM向TC注册分支事务,将其纳入XID对应全局事务的管辖;
- TM向TC发起针对XID的全局提交或回滚决议;
- TC调度XID下管辖的全部分支事务完成提交或回滚请求。
seata安装过程
-
https://github.com/seata/seata/releases
-
解压到指定目录,并修改conf下的file.conf配置文件(先备份配置文件,防止玩坏)
-
主要修改:自定义事务租名称+事务日志存储模式为db+数据库连接信息
-
修改registry.conf
-
建库seata、建表
测试
新建seata-account-service2001、seata-order-service2002、seata-storage-service2003
application.yml
server:
port: 2003
spring:
application:
name: seata-account-service
cloud:
alibaba:
seata:
tx-service-group: wangyh #file.conf 的组名
nacos:
discovery:
server-addr: localhost:8848
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/seata-account?serverTimezone=UTC&characterEncoding=utf-8
username: root
password: 123456
feign:
hystrix:
enabled: false
mybatis:
mapper-locations: classpath:mapper/*.xml
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-seata</artifactId>
<exclusions>
<exclusion>
<groupId>seata-all</groupId>
<artifactId>io.seata</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-all</artifactId>
<version>0.9.0</version>
</dependency>
将seata配置文件复制到项目中
修改file.conf 将31行处修改成组名
服务层
@GlobalTransactional(name = "order-insert",rollbackFor = Exception.class)
public void insertOrder(Order order){
System.out.println("----------------下订单");
orderDao.insert(order);
System.out.println("-----------------减库存");
storageService.decr(order.getPid(),order.getAccount());
System.out.println("-----------------减余额");
accountService.decr(order.getUid(),order.getPrice());
}