目录
在分布式环境中,单体应用被拆分成微服务应用,原来的三个模块被拆分成三个独立的应用,分别使用三个独立的数据源,业务操作需要调用三个服务来完成。此时每个服务内部的数据一致性由本地事务来保证,但是全局的数据一致性问题没法保证。
一句话来说:一次业务操作需要跨多个数据源或需要跨多个系统进行远程调用,就会产生分布式事务问题
Seata是一款开源的分布式事务解决方案,致力于在微服务架构下提供高性能和简单易用的分布式事务服务。
Seata 中有三大模块,分别是 TM、RM 和 TC。 其中 TM 和 RM 是作为 Seata 的客户端与业务系统集成在一起,TC 作为 Seata 的服务端独立部署。
分布式事务处理过程的一ID+三组件模型
Transaction ID XID:全局唯一的事务ID
Transaction Coordinator (TC):事务协调器,维护全局事务的运行状态,负责协调并驱动全局事务的提交或回滚;
Transaction Manager (TM):控制全局事务的边界,负责开启一个全局事务,并最终发起全局提交或全局回滚的决议;
Resource Manager (RM):控制分支事务,负责分支注册、状态汇报,并接收事务协调器的指令,驱动分支(本地)事务的提交和回滚
分布式事务执行的过程:
1.TM 向 TC 注册全局事务,全局事务创建成功并生成一个全局唯一的 XID;
2.XID 在微服务调用链路的上下文中传播;
3.RM 向 TC 注册分支事务,将其纳入 XID 对应全局事务的管辖(根据业务要求编排数据库、服务等事务内资源);
4.TM 向 TC 通知针对 XID 的全局提交/回滚决议;(一阶段结束)5.TC汇总事务信息,决定分布式事务是提交还是回滚;
6.TC 通知 XID 下管辖的全部分支事务(RM)完成提交/回滚请求。(二阶段结束)
通俗解释TM、TC、RM的关系(班主任打算开线上班会):
班长(TM)、班主任(TC)、学生(RM)
1.班长:”王主任,马上到上网课的时间了,你把房间号发一下吧!”
2.班主任:”好的,小王。房间号是8848,我发在班级群里了!”
3.同学们看到了群消息,各自打开XX会议,进入了8848房间... ...
4.班长:”王主任,同学们基本都到齐了,我看您可以开始讲了!”(一阶段结束)
5.班主任突然接到了一通神秘的电话... ....
6.稍等片刻后,班主任:”同学们,我现在通知一个事情(同学们没白等O(∩_∩)O)/不好意思浪费各位的时间,通知临时取消,散了吧(同学们白等了这么长时间 ┭┮﹏┭┮)......“(二阶段结束)
AT模式是seata提供的默认模式,是一种对业务无任何侵入的分布式事务解决方案
在 AT 模式下,用户只需关注自己的“业务 SQL”,用户的 “业务 SQL” 作为一阶段,Seata 框架会自动生成事务的二阶段提交和回滚操作。
AT模式如何做到无侵入?
在一阶段,Seata 会拦截“业务 SQL”
1 解析 SQL 语义,找到“业务 SQL”要更新的业务数据,在业务数据被更新前,将其保存成“before image”,
2 执行“业务 SQL”更新业务数据,3.在业务数据更新之后,其保存成“after image”,最后生成行锁。
以上操作全部在一个数据库事务内完成,这样保证了一阶段操作的原子性。(before image、after image都在保存在 undolog 中)
二阶段如是顺利提交的话(业务顺利执行),因为“业务 SQL”在一阶段已经提交至数据库,所以Seata框架只需将一阶段保存的快照数据和行锁删掉,完成数据清理即可。
二阶段如果是回滚的话(业务某环节出错抛异常),Seata 就需要回滚一阶段已经执行的“业务 SQL”,还原业务数据。回滚方式便是用“before image”还原业务数据;但在还原前要首先要校验脏写,对比“数据库当前业务数据”和 “after image”,如果两份数据完全一致就说明没有脏写,可以还原业务数据,如果不一致就说明有脏写,出现脏写就需要转人工处理。
当全局回滚发生时,server会发送一个回滚消息到client端,client接到回滚通知后,通过xid跟branchid找到对应的undolog,获取到事务执行前后的数据镜像,解析成反向sql进行补偿。
1.首先准备好压缩包,例如:seata-server-0.9.0
2.解压压缩包,打开 conf/file.conf
2.1 修改server模块的组名,名字随意
2.2 修改数据库的信息
注:我用的是mysql8.x,url和driver-class-name与mysql5.x都有所不同,并且需要去lib文件夹内删除原来的mysql-connecter-java.jar , 把8.x版本的jar包拷贝进去
3.修改 conf/registry.conf ,配置nacos的地址
4.在数据库中创建seata数据库,执行 conf/db_store.sql 脚本(若conf内没有就去官网找)
5.在启动了nacos的前提下去执行 bin/seata-server.bat
这里我们会创建三个服务,一个订单服务,一个库存服务,一个账户服务。
当用户下单时,会在订单服务中创建一个订单,然后通过远程调用库存服务来扣减下单商品的库存,再通过远程调用账户服务来扣减用户账户里面的余额,最后在订单服务中修改订单状态为已完成。
该操作跨越三个数据库,有两次远程调用,很明显会有分布式事务问题。
- 1.CREATE DATABASE seata_order; #订单
- CREATE TABLE t_order (
- `id` BIGINT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
- `user_id` BIGINT(11) DEFAULT NULL COMMENT '用户id',
- `product_id` BIGINT(11) DEFAULT NULL COMMENT '产品id',
- `count` INT(11) DEFAULT NULL COMMENT '数量',
- `money` DECIMAL(11,0) DEFAULT NULL COMMENT '金额',
- `status` INT(1) DEFAULT NULL COMMENT '订单状态:0:创建中;1:已完结'
- ) ENGINE=INNODB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
-
- 2.CREATE DATABASE seata_storage; #库存
-
- CREATE TABLE t_storage (
- `id` BIGINT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
- `product_id` BIGINT(11) DEFAULT NULL COMMENT '产品id',
- `total` INT(11) DEFAULT NULL COMMENT '总库存',
- `used` INT(11) DEFAULT NULL COMMENT '已用库存',
- `residue` INT(11) DEFAULT NULL COMMENT '剩余库存'
- ) ENGINE=INNODB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
-
-
- INSERT INTO seata_storage.t_storage(`id`, `product_id`, `total`, `used`, `residue`)
- VALUES ('1', '1', '100', '0', '100');
-
- 3.CREATE DATABASE seata_account; #账户
-
- CREATE TABLE t_account (
- `id` BIGINT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT 'id',
- `user_id` BIGINT(11) DEFAULT NULL COMMENT '用户id',
- `total` DECIMAL(10,0) DEFAULT NULL COMMENT '总额度',
- `used` DECIMAL(10,0) DEFAULT NULL COMMENT '已用余额',
- `residue` DECIMAL(10,0) DEFAULT '0' COMMENT '剩余可用额度'
- ) ENGINE=INNODB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
-
- INSERT INTO seata_account.t_account(`id`, `user_id`, `total`, `used`, `residue`) VALUES ('1', '1', '1000', '0', '1000');
按照上述3库分别建对应的回滚日志表,脚本为conf/db_undo_log.sql,若没有去官网下
- drop table `undo_log`;
- 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,
- `ext` varchar(100) DEFAULT NULL,
- PRIMARY KEY (`id`),
- UNIQUE KEY `ux_undo_log` (`xid`,`branch_id`)
- ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
1.新建Order-Module
2.POM
- <dependencies>
-
- <dependency>
- <groupId>com.alibaba.cloudgroupId>
- <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
- dependency>
-
- <dependency>
- <groupId>com.alibaba.cloudgroupId>
- <artifactId>spring-cloud-starter-alibaba-seataartifactId>
- <exclusions>
- <exclusion>
- <artifactId>seata-allartifactId>
- <groupId>io.seatagroupId>
- exclusion>
- exclusions>
- dependency>
- <dependency>
- <groupId>io.seatagroupId>
- <artifactId>seata-allartifactId>
- <version>0.9.0version>
- dependency>
-
- <dependency>
- <groupId>org.springframework.cloudgroupId>
- <artifactId>spring-cloud-starter-openfeignartifactId>
- dependency>
-
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-webartifactId>
- dependency>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-actuatorartifactId>
- dependency>
-
- <dependency>
- <groupId>mysqlgroupId>
- <artifactId>mysql-connector-javaartifactId>
- <version>8.0.26version>
- dependency>
- <dependency>
- <groupId>com.alibabagroupId>
- <artifactId>druid-spring-boot-starterartifactId>
- <version>1.1.10version>
- dependency>
- <dependency>
- <groupId>org.mybatis.spring.bootgroupId>
- <artifactId>mybatis-spring-boot-starterartifactId>
- <version>2.0.0version>
- dependency>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-testartifactId>
- <scope>testscope>
- dependency>
- <dependency>
- <groupId>org.projectlombokgroupId>
- <artifactId>lombokartifactId>
- <optional>trueoptional>
- dependency>
- dependencies>
3.YML
- server:
- port: 2001
-
- spring:
- application:
- name: seata-order-service
- cloud:
- alibaba:
- seata:
- #自定义事务组名称需要与seata-server中的对应
- tx-service-group: wz_tx_group
- nacos:
- discovery:
- server-addr: localhost:8848
- datasource:
- driver-class-name: com.mysql.cj.jdbc.Driver
- url: jdbc:mysql://localhost:3306/seata_order?serverTimeZone=UTC
- username: root
- password: xxx
-
- feign:
- hystrix:
- enabled: false
-
- logging:
- level:
- io:
- seata: info
-
- mybatis:
- mapperLocations: classpath*:mapper/*.xml
4.domain
- @Data
- @AllArgsConstructor
- @NoArgsConstructor
- public class CommonResult
- {
- private Integer code;
- private String message;
- private T data;
-
- public CommonResult(Integer code, String message)
- {
- this(code,message,null);
- }
- }
- @Data
- @AllArgsConstructor
- @NoArgsConstructor
- public class Order
- {
- private Long id;
-
- private Long userId;
-
- private Long productId;
-
- private Integer count;
-
- private BigDecimal money;
-
- /**
- * 订单状态:0:创建中;1:已完结
- */
- private Integer status;
- }
5.Dao与mapper.xml
- @Mapper
- public interface OrderDao {
-
- /**
- * 创建订单
- */
- void create(Order order);
-
- /**
- * 修改订单金额
- */
- void update(@Param("userId") Long userId, @Param("status") Integer status);
- }
-
- "1.0" encoding="UTF-8" ?>
- mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
-
- <mapper namespace="com.atguigu.springcloud.alibaba.dao.OrderDao">
-
- <resultMap id="BaseResultMap" type="com.atguigu.springcloud.alibaba.domain.Order">
- <id column="id" property="id" jdbcType="BIGINT"/>
- <result column="user_id" property="userId" jdbcType="BIGINT"/>
- <result column="product_id" property="productId" jdbcType="BIGINT"/>
- <result column="count" property="count" jdbcType="INTEGER"/>
- <result column="money" property="money" jdbcType="DECIMAL"/>
- <result column="status" property="status" jdbcType="INTEGER"/>
- resultMap>
-
- <insert id="create">
- INSERT INTO `t_order` (`id`, `user_id`, `product_id`, `count`, `money`, `status`)
- VALUES (NULL, #{userId}, #{productId}, #{count}, #{money}, 0);
- insert>
-
- <update id="update">
- UPDATE `t_order`
- SET status = 1
- WHERE user_id = #{userId} AND status = #{status};
- update>
- mapper>
6.Service
- public interface OrderService {
-
- /**
- * 创建订单
- */
- void create(Order order);
- }
- @Service
- @Slf4j
- public class OrderServiceImpl implements OrderService
- {
- @Resource
- private OrderDao orderDao;
-
- @Resource
- private StorageService storageService;
-
- @Resource
- private AccountService accountService;
-
- /**
- * 创建订单->调用库存服务扣减库存->调用账户服务扣减账户余额->修改订单状态
- * 简单说:
- * 下订单->减库存->减余额->改状态
- */
- @Override
- @GlobalTransactional(name = "fsp-create-order",rollbackFor = Exception.class)
- public void create(Order order) {
- log.info("------->下单开始");
- //本应用创建订单
- orderDao.create(order);
-
- //远程调用库存服务扣减库存
- log.info("------->order-service中扣减库存开始");
- storageService.decrease(order.getProductId(),order.getCount());
- log.info("------->order-service中扣减库存结束");
-
- //远程调用账户服务扣减余额
- log.info("------->order-service中扣减余额开始");
- accountService.decrease(order.getUserId(),order.getMoney());
- log.info("------->order-service中扣减余额结束");
-
- //修改订单状态为已完成
- log.info("------->order-service中修改订单状态开始");
- orderDao.update(order.getUserId(),0);
- log.info("------->order-service中修改订单状态结束");
-
- log.info("------->下单结束");
- }
- }
- @FeignClient(value = "seata-storage-service")
- public interface StorageService {
-
- /**
- * 扣减库存
- */
- @PostMapping(value = "/storage/decrease")
- CommonResult decrease(@RequestParam("productId") Long productId, @RequestParam("count") Integer count);
- }
- @FeignClient(value = "seata-account-service")
- public interface AccountService {
-
- /**
- * 扣减账户余额
- */
- //@RequestMapping(value = "/account/decrease", method = RequestMethod.POST, produces = "application/json; charset=UTF-8")
- @PostMapping("/account/decrease")
- CommonResult decrease(@RequestParam("userId") Long userId, @RequestParam("money") BigDecimal money);
- }
7.Controller
- @RestController
- public class OrderController {
-
- @Autowired
- private OrderService orderService;
-
- /**
- * 创建订单
- */
- @GetMapping("/order/create")
- public CommonResult create( Order order) {
- orderService.create(order);
- return new CommonResult(200, "订单创建成功!");
- }
- }
8.Config
- @Configuration
- @MapperScan({"com.atguigu.springcloud.alibaba.dao"})
- public class MyBatisConfig {
- }
- @Configuration
- public class DataSourceProxyConfig {
-
- @Value("${mybatis.mapperLocations}")
- private String mapperLocations;
-
- @Bean
- @ConfigurationProperties(prefix = "spring.datasource")
- public DataSource druidDataSource(){
- return new DruidDataSource();
- }
-
- @Bean
- public DataSourceProxy dataSourceProxy(DataSource dataSource) {
- return new DataSourceProxy(dataSource);
- }
-
- @Bean
- public SqlSessionFactory sqlSessionFactoryBean(DataSourceProxy dataSourceProxy) throws Exception {
- SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
- sqlSessionFactoryBean.setDataSource(dataSourceProxy);
- sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
- sqlSessionFactoryBean.setTransactionFactory(new SpringManagedTransactionFactory());
- return sqlSessionFactoryBean.getObject();
- }
-
- }
9.主启动
- @EnableDiscoveryClient
- @EnableFeignClients
- @SpringBootApplication(exclude = DataSourceAutoConfiguration.class)//取消数据源的自动创建
- public class SeataOrderMainApp2001
- {
-
- public static void main(String[] args)
- {
- SpringApplication.run(SeataOrderMainApp2001.class, args);
- }
- }
10.file.conf
- transport {
- # tcp udt unix-domain-socket
- type = "TCP"
- #NIO NATIVE
- server = "NIO"
- #enable heartbeat
- heartbeat = true
- #thread factory for netty
- thread-factory {
- boss-thread-prefix = "NettyBoss"
- worker-thread-prefix = "NettyServerNIOWorker"
- server-executor-thread-prefix = "NettyServerBizHandler"
- share-boss-worker = false
- client-selector-thread-prefix = "NettyClientSelector"
- client-selector-thread-size = 1
- client-worker-thread-prefix = "NettyClientWorkerThread"
- # netty boss thread size,will not be used for UDT
- boss-thread-size = 1
- #auto default pin or 8
- worker-thread-size = 8
- }
- shutdown {
- # when destroy server, wait seconds
- wait = 3
- }
- serialization = "seata"
- compressor = "none"
- }
-
- service {
-
- vgroup_mapping.wz_tx_group = "default" #修改自定义事务组名称
-
- default.grouplist = "127.0.0.1:8091"
- enableDegrade = false
- disable = false
- max.commit.retry.timeout = "-1"
- max.rollback.retry.timeout = "-1"
- disableGlobalTransaction = false
- }
-
-
- client {
- async.commit.buffer.limit = 10000
- lock {
- retry.internal = 10
- retry.times = 30
- }
- report.retry.count = 5
- tm.commit.retry.count = 1
- tm.rollback.retry.count = 1
- }
-
- ## transaction log store
- store {
- ## store mode: file、db
- mode = "db"
-
- ## file store
- file {
- dir = "sessionStore"
-
- # branch session size , if exceeded first try compress lockkey, still exceeded throws exceptions
- max-branch-session-size = 16384
- # globe session size , if exceeded throws exceptions
- max-global-session-size = 512
- # file buffer size , if exceeded allocate new buffer
- file-write-buffer-cache-size = 16384
- # when recover batch read size
- session.reload.read_size = 100
- # async, sync
- flush-disk-mode = async
- }
-
- ## database store
- db {
- ## the implement of javax.sql.DataSource, such as DruidDataSource(druid)/BasicDataSource(dbcp) etc.
- datasource = "dbcp"
- ## mysql/oracle/h2/oceanbase etc.
- db-type = "mysql"
- driver-class-name = "com.mysql.cj.jdbc.Driver"
- url = "jdbc:mysql://127.0.0.1:3306/seata?serverTimeZone=UTC"
- user = "root"
- password = "xxx"
- min-conn = 1
- max-conn = 3
- global.table = "global_table"
- branch.table = "branch_table"
- lock-table = "lock_table"
- query-limit = 100
- }
- }
- lock {
- ## the lock store mode: local、remote
- mode = "remote"
-
- local {
- ## store locks in user's database
- }
-
- remote {
- ## store locks in the seata's server
- }
- }
- recovery {
- #schedule committing retry period in milliseconds
- committing-retry-period = 1000
- #schedule asyn committing retry period in milliseconds
- asyn-committing-retry-period = 1000
- #schedule rollbacking retry period in milliseconds
- rollbacking-retry-period = 1000
- #schedule timeout retry period in milliseconds
- timeout-retry-period = 1000
- }
-
- transaction {
- undo.data.validation = true
- undo.log.serialization = "jackson"
- undo.log.save.days = 7
- #schedule delete expired undo_log in milliseconds
- undo.log.delete.period = 86400000
- undo.log.table = "undo_log"
- }
-
- ## metrics settings
- metrics {
- enabled = false
- registry-type = "compact"
- # multi exporters use comma divided
- exporter-list = "prometheus"
- exporter-prometheus-port = 9898
- }
-
- support {
- ## spring
- spring {
- # auto proxy the DataSource bean
- datasource.autoproxy = false
- }
- }
-
11.registry.conf
- registry {
- # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
- type = "nacos"
-
- nacos {
- serverAddr = "localhost:8848"
- namespace = ""
- cluster = "default"
- }
- eureka {
- serviceUrl = "http://localhost:8761/eureka"
- application = "default"
- weight = "1"
- }
- redis {
- serverAddr = "localhost:6379"
- db = "0"
- }
- zk {
- cluster = "default"
- serverAddr = "127.0.0.1:2181"
- session.timeout = 6000
- connect.timeout = 2000
- }
- consul {
- cluster = "default"
- serverAddr = "127.0.0.1:8500"
- }
- etcd3 {
- cluster = "default"
- serverAddr = "http://localhost:2379"
- }
- sofa {
- serverAddr = "127.0.0.1:9603"
- application = "default"
- region = "DEFAULT_ZONE"
- datacenter = "DefaultDataCenter"
- cluster = "default"
- group = "SEATA_GROUP"
- addressWaitTime = "3000"
- }
- file {
- name = "file.conf"
- }
- }
-
- config {
- # file、nacos 、apollo、zk、consul、etcd3
- type = "file"
-
- nacos {
- serverAddr = "localhost"
- namespace = ""
- }
- consul {
- serverAddr = "127.0.0.1:8500"
- }
- apollo {
- app.id = "seata-server"
- apollo.meta = "http://192.168.1.204:8801"
- }
- zk {
- serverAddr = "127.0.0.1:2181"
- session.timeout = 6000
- connect.timeout = 2000
- }
- etcd3 {
- serverAddr = "http://localhost:2379"
- }
- file {
- name = "file.conf"
- }
- }
1.新建Storage-Module
2.POM
- <dependencies>
-
- <dependency>
- <groupId>com.alibaba.cloudgroupId>
- <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
- dependency>
-
- <dependency>
- <groupId>com.alibaba.cloudgroupId>
- <artifactId>spring-cloud-starter-alibaba-seataartifactId>
- <exclusions>
- <exclusion>
- <artifactId>seata-allartifactId>
- <groupId>io.seatagroupId>
- exclusion>
- exclusions>
- dependency>
- <dependency>
- <groupId>io.seatagroupId>
- <artifactId>seata-allartifactId>
- <version>0.9.0version>
- dependency>
-
- <dependency>
- <groupId>org.springframework.cloudgroupId>
- <artifactId>spring-cloud-starter-openfeignartifactId>
- dependency>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-webartifactId>
- dependency>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-testartifactId>
- <scope>testscope>
- dependency>
- <dependency>
- <groupId>org.mybatis.spring.bootgroupId>
- <artifactId>mybatis-spring-boot-starterartifactId>
- <version>2.0.0version>
- dependency>
- <dependency>
- <groupId>mysqlgroupId>
- <artifactId>mysql-connector-javaartifactId>
- <version>8.0.26version>
- dependency>
- <dependency>
- <groupId>com.alibabagroupId>
- <artifactId>druid-spring-boot-starterartifactId>
- <version>1.1.10version>
- dependency>
- <dependency>
- <groupId>org.projectlombokgroupId>
- <artifactId>lombokartifactId>
- <optional>trueoptional>
- dependency>
- dependencies>
3.YML
- server:
- port: 2002
-
- spring:
- application:
- name: seata-storage-service
- cloud:
- alibaba:
- seata:
- tx-service-group: wz_tx_group
- nacos:
- discovery:
- server-addr: localhost:8848
- datasource:
- driver-class-name: com.mysql.cj.jdbc.Driver
- url: jdbc:mysql://localhost:3306/seata_storage?serverTimeZone=UTC
- username: root
- password: xxx
-
- logging:
- level:
- io:
- seata: info
-
- mybatis:
- mapperLocations: classpath*:mapper/*.xml
-
-
4.domain
- @Data
- @AllArgsConstructor
- @NoArgsConstructor
- public class CommonResult
- {
- private Integer code;
- private String message;
- private T data;
-
- public CommonResult(Integer code, String message)
- {
- this(code,message,null);
- }
- }
- @Data
- public class Storage {
-
- private Long id;
-
- /**
- * 产品id
- */
- private Long productId;
-
- /**
- * 总库存
- */
- private Integer total;
-
- /**
- * 已用库存
- */
- private Integer used;
-
- /**
- * 剩余库存
- */
- private Integer residue;
- }
5.Dao
- @Mapper
- public interface StorageDao {
-
- //扣减库存
- void decrease(@Param("productId") Long productId, @Param("count") Integer count);
- }
6.Service
- public interface StorageService {
- /**
- * 扣减库存
- */
- void decrease(Long productId, Integer count);
- }
- @Service
- public class StorageServiceImpl implements StorageService {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(StorageServiceImpl.class);
-
- @Resource
- private StorageDao storageDao;
-
- /**
- * 扣减库存
- */
- @Override
- public void decrease(Long productId, Integer count) {
- LOGGER.info("------->storage-service中扣减库存开始");
- storageDao.decrease(productId,count);
- LOGGER.info("------->storage-service中扣减库存结束");
- }
- }
7.Controller
- @RestController
- public class StorageController {
-
- @Autowired
- private StorageService storageService;
-
- /**
- * 扣减库存
- */
- @RequestMapping("/storage/decrease")
- public CommonResult decrease(Long productId, Integer count) {
- storageService.decrease(productId, count);
- return new CommonResult(200,"扣减库存成功!");
- }
- }
8.Config
- @Configuration
- public class DataSourceProxyConfig {
-
- @Value("${mybatis.mapperLocations}")
- private String mapperLocations;
-
- @Bean
- @ConfigurationProperties(prefix = "spring.datasource")
- public DataSource druidDataSource(){
- return new DruidDataSource();
- }
-
- @Bean
- public DataSourceProxy dataSourceProxy(DataSource dataSource) {
- return new DataSourceProxy(dataSource);
- }
-
- @Bean
- public SqlSessionFactory sqlSessionFactoryBean(DataSourceProxy dataSourceProxy) throws Exception {
- SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
- sqlSessionFactoryBean.setDataSource(dataSourceProxy);
- sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
- sqlSessionFactoryBean.setTransactionFactory(new SpringManagedTransactionFactory());
- return sqlSessionFactoryBean.getObject();
- }
-
- }
- @Configuration
- @MapperScan({"com.atguigu.springcloud.alibaba.dao"})
- public class MyBatisConfig {
- }
9.主启动
- @SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
- @EnableDiscoveryClient
- @EnableFeignClients
- public class SeataStorageServiceApplication2002
- {
- public static void main(String[] args)
- {
- SpringApplication.run(SeataStorageServiceApplication2002.class, args);
- }
- }
10.file.conf
- transport {
- # tcp udt unix-domain-socket
- type = "TCP"
- #NIO NATIVE
- server = "NIO"
- #enable heartbeat
- heartbeat = true
- #thread factory for netty
- thread-factory {
- boss-thread-prefix = "NettyBoss"
- worker-thread-prefix = "NettyServerNIOWorker"
- server-executor-thread-prefix = "NettyServerBizHandler"
- share-boss-worker = false
- client-selector-thread-prefix = "NettyClientSelector"
- client-selector-thread-size = 1
- client-worker-thread-prefix = "NettyClientWorkerThread"
- # netty boss thread size,will not be used for UDT
- boss-thread-size = 1
- #auto default pin or 8
- worker-thread-size = 8
- }
- shutdown {
- # when destroy server, wait seconds
- wait = 3
- }
- serialization = "seata"
- compressor = "none"
- }
-
- service {
- #vgroup->rgroup
- vgroup_mapping.wz_tx_group = "default"
- #only support single node
- default.grouplist = "127.0.0.1:8091"
- #degrade current not support
- enableDegrade = false
- #disable
- disable = false
- #unit ms,s,m,h,d represents milliseconds, seconds, minutes, hours, days, default permanent
- max.commit.retry.timeout = "-1"
- max.rollback.retry.timeout = "-1"
- disableGlobalTransaction = false
- }
-
- client {
- async.commit.buffer.limit = 10000
- lock {
- retry.internal = 10
- retry.times = 30
- }
- report.retry.count = 5
- tm.commit.retry.count = 1
- tm.rollback.retry.count = 1
- }
-
- transaction {
- undo.data.validation = true
- undo.log.serialization = "jackson"
- undo.log.save.days = 7
- #schedule delete expired undo_log in milliseconds
- undo.log.delete.period = 86400000
- undo.log.table = "undo_log"
- }
-
- support {
- ## spring
- spring {
- # auto proxy the DataSource bean
- datasource.autoproxy = false
- }
- }
-
-
11.registry.conf
- registry {
- # file 、nacos 、eureka、redis、zk
- type = "nacos"
-
- nacos {
- serverAddr = "localhost:8848"
- namespace = ""
- cluster = "default"
- }
- eureka {
- serviceUrl = "http://localhost:8761/eureka"
- application = "default"
- weight = "1"
- }
- redis {
- serverAddr = "localhost:6381"
- db = "0"
- }
- zk {
- cluster = "default"
- serverAddr = "127.0.0.1:2181"
- session.timeout = 6000
- connect.timeout = 2000
- }
- file {
- name = "file.conf"
- }
- }
-
- config {
- # file、nacos 、apollo、zk
- type = "file"
-
- nacos {
- serverAddr = "localhost"
- namespace = ""
- cluster = "default"
- }
- apollo {
- app.id = "fescar-server"
- apollo.meta = "http://192.168.1.204:8801"
- }
- zk {
- serverAddr = "127.0.0.1:2181"
- session.timeout = 6000
- connect.timeout = 2000
- }
- file {
- name = "file.conf"
- }
- }
-
-
-
1.新建Account-Module
2.POM
- <dependencies>
-
- <dependency>
- <groupId>com.alibaba.cloudgroupId>
- <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
- dependency>
-
- <dependency>
- <groupId>com.alibaba.cloudgroupId>
- <artifactId>spring-cloud-starter-alibaba-seataartifactId>
- <exclusions>
- <exclusion>
- <artifactId>seata-allartifactId>
- <groupId>io.seatagroupId>
- exclusion>
- exclusions>
- dependency>
- <dependency>
- <groupId>io.seatagroupId>
- <artifactId>seata-allartifactId>
- <version>0.9.0version>
- dependency>
-
- <dependency>
- <groupId>org.springframework.cloudgroupId>
- <artifactId>spring-cloud-starter-openfeignartifactId>
- dependency>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-webartifactId>
- dependency>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-testartifactId>
- <scope>testscope>
- dependency>
- <dependency>
- <groupId>org.mybatis.spring.bootgroupId>
- <artifactId>mybatis-spring-boot-starterartifactId>
- <version>2.0.0version>
- dependency>
- <dependency>
- <groupId>mysqlgroupId>
- <artifactId>mysql-connector-javaartifactId>
- <version>8.0.26version>
- dependency>
- <dependency>
- <groupId>com.alibabagroupId>
- <artifactId>druid-spring-boot-starterartifactId>
- <version>1.1.10version>
- dependency>
- <dependency>
- <groupId>org.projectlombokgroupId>
- <artifactId>lombokartifactId>
- <optional>trueoptional>
- dependency>
- dependencies>
3.YML
- server:
- port: 2003
-
- spring:
- application:
- name: seata-account-service
- cloud:
- alibaba:
- seata:
- tx-service-group: wz_tx_group
- nacos:
- discovery:
- server-addr: localhost:8848
- datasource:
- driver-class-name: com.mysql.cj.jdbc.Driver
- url: jdbc:mysql://localhost:3306/seata_account?serverTimeZone=UTC
- username: root
- password: xxx
-
- feign:
- hystrix:
- enabled: false
-
- logging:
- level:
- io:
- seata: info
-
- mybatis:
- mapperLocations: classpath*:mapper/*.xml
-
-
4.domain
- @Data
- @AllArgsConstructor
- @NoArgsConstructor
- public class Account {
-
- private Long id;
-
- /**
- * 用户id
- */
- private Long userId;
-
- /**
- * 总额度
- */
- private BigDecimal total;
-
- /**
- * 已用额度
- */
- private BigDecimal used;
-
- /**
- * 剩余额度
- */
- private BigDecimal residue;
- }
- @Data
- @AllArgsConstructor
- @NoArgsConstructor
- public class CommonResult
- {
- private Integer code;
- private String message;
- private T data;
-
- public CommonResult(Integer code, String message)
- {
- this(code,message,null);
- }
- }
5.Dao
- @Mapper
- public interface AccountDao {
-
- /**
- * 扣减账户余额
- */
- void decrease(@Param("userId") Long userId, @Param("money") BigDecimal money);
- }
6.Service
- public interface AccountService {
-
- /**
- * 扣减账户余额
- * @param userId 用户id
- * @param money 金额
- */
- void decrease(@RequestParam("userId") Long userId, @RequestParam("money") BigDecimal money);
- }
- @Service
- public class AccountServiceImpl implements AccountService {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(AccountServiceImpl.class);
-
-
- @Resource
- AccountDao accountDao;
-
- /**
- * 扣减账户余额
- */
- @Override
- public void decrease(Long userId, BigDecimal money) {
- LOGGER.info("------->account-service中扣减账户余额开始");
- //模拟超时异常,全局事务回滚
- //暂停几秒钟线程
- try { TimeUnit.SECONDS.sleep(20); } catch (InterruptedException e) { e.printStackTrace(); }
- accountDao.decrease(userId,money);
- LOGGER.info("------->account-service中扣减账户余额结束");
- }
- }
7.Controller
- @RestController
- public class AccountController {
-
- @Resource
- AccountService accountService;
-
- /**
- * 扣减账户余额
- */
- @RequestMapping("/account/decrease")
- public CommonResult decrease(@RequestParam("userId") Long userId, @RequestParam("money") BigDecimal money){
- accountService.decrease(userId,money);
- return new CommonResult(200,"扣减账户余额成功!");
- }
- }
8.Config
- @Configuration
- @MapperScan({"com.atguigu.springcloud.alibaba.dao"})
- public class MyBatisConfig {
- }
- @Configuration
- public class DataSourceProxyConfig {
-
- @Value("${mybatis.mapperLocations}")
- private String mapperLocations;
-
- @Bean
- @ConfigurationProperties(prefix = "spring.datasource")
- public DataSource druidDataSource(){
- return new DruidDataSource();
- }
-
- @Bean
- public DataSourceProxy dataSourceProxy(DataSource dataSource) {
- return new DataSourceProxy(dataSource);
- }
-
- @Bean
- public SqlSessionFactory sqlSessionFactoryBean(DataSourceProxy dataSourceProxy) throws Exception {
- SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
- sqlSessionFactoryBean.setDataSource(dataSourceProxy);
- sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
- sqlSessionFactoryBean.setTransactionFactory(new SpringManagedTransactionFactory());
- return sqlSessionFactoryBean.getObject();
- }
-
- }
9.主启动
- @SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
- @EnableDiscoveryClient
- @EnableFeignClients
- public class SeataAccountMainApp2003
- {
- public static void main(String[] args)
- {
- SpringApplication.run(SeataAccountMainApp2003.class, args);
- }
- }
10.file.conf
- transport {
- # tcp udt unix-domain-socket
- type = "TCP"
- #NIO NATIVE
- server = "NIO"
- #enable heartbeat
- heartbeat = true
- #thread factory for netty
- thread-factory {
- boss-thread-prefix = "NettyBoss"
- worker-thread-prefix = "NettyServerNIOWorker"
- server-executor-thread-prefix = "NettyServerBizHandler"
- share-boss-worker = false
- client-selector-thread-prefix = "NettyClientSelector"
- client-selector-thread-size = 1
- client-worker-thread-prefix = "NettyClientWorkerThread"
- # netty boss thread size,will not be used for UDT
- boss-thread-size = 1
- #auto default pin or 8
- worker-thread-size = 8
- }
- shutdown {
- # when destroy server, wait seconds
- wait = 3
- }
- serialization = "seata"
- compressor = "none"
- }
-
- service {
-
- vgroup_mapping.wz_tx_group = "default" #修改自定义事务组名称
-
- default.grouplist = "127.0.0.1:8091"
- enableDegrade = false
- disable = false
- max.commit.retry.timeout = "-1"
- max.rollback.retry.timeout = "-1"
- disableGlobalTransaction = false
- }
-
-
- client {
- async.commit.buffer.limit = 10000
- lock {
- retry.internal = 10
- retry.times = 30
- }
- report.retry.count = 5
- tm.commit.retry.count = 1
- tm.rollback.retry.count = 1
- }
-
- ## transaction log store
- store {
- ## store mode: file、db
- mode = "db"
-
- ## file store
- file {
- dir = "sessionStore"
-
- # branch session size , if exceeded first try compress lockkey, still exceeded throws exceptions
- max-branch-session-size = 16384
- # globe session size , if exceeded throws exceptions
- max-global-session-size = 512
- # file buffer size , if exceeded allocate new buffer
- file-write-buffer-cache-size = 16384
- # when recover batch read size
- session.reload.read_size = 100
- # async, sync
- flush-disk-mode = async
- }
-
- ## database store
- db {
- ## the implement of javax.sql.DataSource, such as DruidDataSource(druid)/BasicDataSource(dbcp) etc.
- datasource = "dbcp"
- ## mysql/oracle/h2/oceanbase etc.
- db-type = "mysql"
- driver-class-name = "com.mysql.cj.jdbc.Driver"
- url = "jdbc:mysql://172.0.0.1:3306/seata_account?serverTimeZone=UTC"
- user = "root"
- password = "xxx"
- min-conn = 1
- max-conn = 3
- global.table = "global_table"
- branch.table = "branch_table"
- lock-table = "lock_table"
- query-limit = 100
- }
- }
- lock {
- ## the lock store mode: local、remote
- mode = "remote"
-
- local {
- ## store locks in user's database
- }
-
- remote {
- ## store locks in the seata's server
- }
- }
- recovery {
- #schedule committing retry period in milliseconds
- committing-retry-period = 1000
- #schedule asyn committing retry period in milliseconds
- asyn-committing-retry-period = 1000
- #schedule rollbacking retry period in milliseconds
- rollbacking-retry-period = 1000
- #schedule timeout retry period in milliseconds
- timeout-retry-period = 1000
- }
-
- transaction {
- undo.data.validation = true
- undo.log.serialization = "jackson"
- undo.log.save.days = 7
- #schedule delete expired undo_log in milliseconds
- undo.log.delete.period = 86400000
- undo.log.table = "undo_log"
- }
-
- ## metrics settings
- metrics {
- enabled = false
- registry-type = "compact"
- # multi exporters use comma divided
- exporter-list = "prometheus"
- exporter-prometheus-port = 9898
- }
-
- support {
- ## spring
- spring {
- # auto proxy the DataSource bean
- datasource.autoproxy = false
- }
- }
11.registry.conf
- registry {
- # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
- type = "nacos"
-
- nacos {
- serverAddr = "localhost:8848"
- namespace = ""
- cluster = "default"
- }
- eureka {
- serviceUrl = "http://localhost:8761/eureka"
- application = "default"
- weight = "1"
- }
- redis {
- serverAddr = "localhost:6379"
- db = "0"
- }
- zk {
- cluster = "default"
- serverAddr = "127.0.0.1:2181"
- session.timeout = 6000
- connect.timeout = 2000
- }
- consul {
- cluster = "default"
- serverAddr = "127.0.0.1:8500"
- }
- etcd3 {
- cluster = "default"
- serverAddr = "http://localhost:2379"
- }
- sofa {
- serverAddr = "127.0.0.1:9603"
- application = "default"
- region = "DEFAULT_ZONE"
- datacenter = "DefaultDataCenter"
- cluster = "default"
- group = "SEATA_GROUP"
- addressWaitTime = "3000"
- }
- file {
- name = "file.conf"
- }
- }
-
- config {
- # file、nacos 、apollo、zk、consul、etcd3
- type = "file"
-
- nacos {
- serverAddr = "localhost"
- namespace = ""
- }
- consul {
- serverAddr = "127.0.0.1:8500"
- }
- apollo {
- app.id = "seata-server"
- apollo.meta = "http://192.168.1.204:8801"
- }
- zk {
- serverAddr = "127.0.0.1:2181"
- session.timeout = 6000
- connect.timeout = 2000
- }
- etcd3 {
- serverAddr = "http://localhost:2379"
- }
- file {
- name = "file.conf"
- }
- }
-
-
-
注意我们在AccountServiceImpl添加超时:
- //模拟超时异常,全局事务回滚
- //暂停几秒钟线程
- try { TimeUnit.SECONDS.sleep(20); } ... ...
输入:
http://localhost:2001/order/create?userId=1&productId=1&count=10&money=100
直接报错了,查看数据库的数据,没有任何改变。
如果我们把OrderServiceImpl中的@GlobalTransactional注解去掉,再尝试,也会报错,但会发现这样的BUG:钱已经扣了,但订单状态仍显示未完成!