目录
- 1.分布式事务问题
- 2.Seata简介
- 2.1 是什么
- 2.2 作用
- 2.3 下载
- 2.4 如何使用
- 3.Seata-Server安装
- 3.1 下载网址
- 3.2 下载版本
- 3.3 seata解压到指定目录并修改文件
- 3.3.1 nacos新增配置文件
- 3.3.2 修改application.yml
- 3.4 数据库新建seata
- 3.5 在seata里建表
- 3.6 启动Nacos端口号8848
- 3.7 启动seata-server
- 4.订单/库存/账户业务数据库准备
- 4.1 分布式事务业务说明
- 4.2 创建业务数据库
- 4.3 按照上述3库分别建对应业务表
- 4.4 按照上述3库分别建对应的回滚日志
- 4.5 最终效果
- 5.订单/库存/账户业务微服务准备
- 5.1 业务需求
- 5.2 新建Order-Module
- 5.2.1 新建seata-order-service2001
- 5.2.2 POM
- 5.2.3 YML
- 5.2.4 修改seata路径下的/conf/application.yml
- 5.2.6 遇到的问题和坑
- 5.2.7 domain
- 5.2.8 Dao接口及实现
- 5.2.9 Service接口及实现
- 5.2.10 Conrtoller
- 5.2.10 Config配置
- 5.2.11 主启动
- 5.3 新建Storage-Module
- 5.3.1 新建seata-storage-service2002
- 5.3.2 POM
- 5.3.3 YML
- 5.3.4 修改seata路径下的/conf/application.yml
- 5.3.5 domain
- 5.3.6 Dao接口及实现
- 5.3.7 Service接口及实现
- 5.3.8 Conrtoller
- 5.3.9 Config配置
- 5.3.10 主启动
- 5.4 新建Account-Module
- 5.4.1 新建seata-account-service2003
- 5.4.2 POM
- 5.4.3 YML
- 5.4.4 修改seata路径下的/conf/application.yml
- 5.4.5 domain
- 5.4.6 Dao接口及实现
- 5.4.7 Service接口及实现
- 5.4.8 Conrtoller
- 5.4.9 Config配置
- 5.4.10 主启动
- 6.测试
- 6.1数据库初始情况
- 6.2 正常下单
- 6.3 超时异常,没加@GlobalTransactional
- 6.4 超时异常,添加@GlobalTransactional
- 7.补充
- 7.1 Seata
- 7.2 再看TC/TM/RM三大组件
- 7.3 AT模式如何做到对业务的无侵入
- 7.3.1 是什么
- 7.3.2 一阶段加载
- 7.3.3 正常情况二阶段提交
- 7.3.4 异常情况二阶段回滚
- 7.4 debug
- 7.5 补充
1.分布式事务问题
分布式前
- 单机单库没有这个问题
- 从1:1到1:N到N:N
分布式后
单体应用被拆分成微服务应用,原来的三个模块被拆分成三个独立的应用
,分别使用三个独立的数据元
业务操作需要调用三个服务来完成,此时每个服务内部的数据一致性由本地事务来保证,但是全局的数据的一致性问题没法保证
概述:一次业务操作需要跨多个数据源或需要跨多系统进行远程调用,就会产生分布式问题
2.Seata简介
2.1 是什么
官网
Seata 是一款开源的分布式事务解决方案,致力于在微服务架构下提供高性能和简单易用的分布式事务服务。在 Seata 开源之前,其内部版本在阿里经济体内部一直扮演着应用架构层数据一致性的中间件角色,帮助经济体平稳的度过历年的双11,对上层业务进行了有力的技术支撑。
2.2 作用
Seata是一个典型的分布式事务过程
分布式事务处理过程的一致性的一ID+三组件模型
一ID: Transaction ID XID 全局唯一的事务ID
三组件概念:
TC (Transaction Coordinator) - 事务协调器,维护全局事务的运行状态,负责协调并驱动全局事务的提交或回滚
TM (Transaction Manager) - 控制全局事务的边界,负责开启一个全局事务,并最终发起全局提交或全局回滚的决议
RM (Resource Manager) - 控制分支事务,负责分支注册、状态汇报,并接收事务协调器的指令,驱动分支(本地)事务的提交和回滚
处理过程
-
TM 向 TC 申请开启一个全局事务,全局事务创建成功并生成一个全局唯一的 XID;
-
XID 在微服务调用链路的上下文中传播;
-
RM 向 TC 注册分支事务,将其纳入 XID 对应全局事务的管辖;
-
TM 向 TC 发起针对 XID 的全局提交或回滚决议;
-
TC 调度 XID 下管辖的全部分支事务完成提交或回滚请求。
2.3 下载
下载网址
2.4 如何使用
本地@Transactional
全局@GlobalTransactional
SEATA分分布式交易解决方案
3.Seata-Server安装
3.1 下载网址
下载网址
3.2 下载版本
3.3 seata解压到指定目录并修改文件
3.3.1 nacos新增配置文件
nacos中新建命名空间
在nacos中添加配置
- Data Id = seataServer.properties
- Group = SEATA_GROUP
store.mode=db
store.lock.mode=db
store.session.mode=db
store.db.datasource=druid
store.db.dbType=mysql
store.db.driverClassName=com.mysql.cj.jdbc.Driver
store.db.url=jdbc:mysql://127.0.0.1:3306/seata?useUnicode=true&rewriteBatchedStatements=true
store.db.user=root
store.db.password=123456
store.db.minConn=5
store.db.maxConn=30
store.db.globalTable=global_table
store.db.branchTable=branch_table
store.db.distributedLockTable=distributed_lock
store.db.queryLimit=100
store.db.lockTable=lock_table
store.db.maxWait=5000
service.vgroupMapping.fsp_tx_group=default
3.3.2 修改application.yml
拷贝一份application.yml
修改application.yml如下
server:
port: 7091
spring:
application:
name: seata-server
logging:
config: classpath:logback-spring.xml
file:
path: ${user.home}/logs/seata
# extend:
# logstash-appender:
# destination: 127.0.0.1:4560
# kafka-appender:
# bootstrap-servers: 127.0.0.1:9092
# topic: logback_to_logstash
console:
user:
username: seata
password: seata
seata:
config:
# support: nacos, consul, apollo, zk, etcd3
type: nacos
nacos:
serverAddr: 127.0.0.1:8848
namespace: #修改为自己的
group: SEATA_GROUP #需要与前面创建的配置文件相对应
username: nacos
password: nacos
file-extension: yaml
shared-configs:
- dataId: seata-server.yaml #需要与前面创建的配置文件相对应
namespace: 6f25df50-1e22-4301-9587-d627b6158fc9 #修改为自己的
group: SEATA_GROUP
registry:
# support: nacos, eureka, redis, zk, consul, etcd3, sofa
type: nacos
nacos:
serverAddr: 127.0.0.1:8848
namespace: #修改为自己的
group: SEATA_GROUP
username: nacos
password: nacos
file-extension: yaml
shared-configs:
- dataId: seata-server.yaml #需要与前面创建的配置文件相对应
namespace: 6f25df50-1e22-4301-9587-d627b6158fc9 #需要与前面创建的配置文件相对应
group: SEATA_GROUP #需要与前面创建的配置文件相对应
#store:
# support: file 、 db 、 redis
#mode: file
# server:
# service-port: 8091 #If not configured, the default is '${server.port} + 1000'
security:
secretKey: SeataSecretKey0c382ef121d778043159209298fd40bf3850a017
tokenValidityInMilliseconds: 1800000
ignore:
urls: /,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-fe/public/**,/api/v1/auth/login
3.4 数据库新建seata
如果是mysql8参考,用seata1.3.0可以用seata0.9.0不行链接
3.5 在seata里建表
-- -------------------------------- The script used when storeMode is 'db' --------------------------------
-- the table to store GlobalSession data
CREATE TABLE IF NOT EXISTS `global_table`
(
`xid` VARCHAR(128) NOT NULL,
`transaction_id` BIGINT,
`status` TINYINT NOT NULL,
`application_id` VARCHAR(32),
`transaction_service_group` VARCHAR(32),
`transaction_name` VARCHAR(128),
`timeout` INT,
`begin_time` BIGINT,
`application_data` VARCHAR(2000),
`gmt_create` DATETIME,
`gmt_modified` DATETIME,
PRIMARY KEY (`xid`),
KEY `idx_status_gmt_modified` (`status` , `gmt_modified`),
KEY `idx_transaction_id` (`transaction_id`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4;
-- the table to store BranchSession data
CREATE TABLE IF NOT EXISTS `branch_table`
(
`branch_id` BIGINT NOT NULL,
`xid` VARCHAR(128) NOT NULL,
`transaction_id` BIGINT,
`resource_group_id` VARCHAR(32),
`resource_id` VARCHAR(256),
`branch_type` VARCHAR(8),
`status` TINYINT,
`client_id` VARCHAR(64),
`application_data` VARCHAR(2000),
`gmt_create` DATETIME(6),
`gmt_modified` DATETIME(6),
PRIMARY KEY (`branch_id`),
KEY `idx_xid` (`xid`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4;
-- the table to store lock data
CREATE TABLE IF NOT EXISTS `lock_table`
(
`row_key` VARCHAR(128) NOT NULL,
`xid` VARCHAR(128),
`transaction_id` BIGINT,
`branch_id` BIGINT NOT NULL,
`resource_id` VARCHAR(256),
`table_name` VARCHAR(32),
`pk` VARCHAR(36),
`status` TINYINT NOT NULL DEFAULT '0' COMMENT '0:locked ,1:rollbacking',
`gmt_create` DATETIME,
`gmt_modified` DATETIME,
PRIMARY KEY (`row_key`),
KEY `idx_status` (`status`),
KEY `idx_branch_id` (`branch_id`),
KEY `idx_xid_and_branch_id` (`xid` , `branch_id`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4;
CREATE TABLE IF NOT EXISTS `distributed_lock`
(
`lock_key` CHAR(20) NOT NULL,
`lock_value` VARCHAR(20) NOT NULL,
`expire` BIGINT,
primary key (`lock_key`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4;
INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('AsyncCommitting', ' ', 0);
INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('RetryCommitting', ' ', 0);
INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('RetryRollbacking', ' ', 0);
INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('TxTimeoutCheck', ' ', 0);
3.6 启动Nacos端口号8848
3.7 启动seata-server
4.订单/库存/账户业务数据库准备
以下演示都需要先启动Nacos后启动Seata
如果Seata没启动会报错no available server to connect
4.1 分布式事务业务说明
业务说明
这里我们创建三个服务,一个订单服务,一个库存服务,一个账户服务
当用户下单时,会在订单服务中创建一个订单,然后通过远程调用库存服务来扣减下单商品的库存,再通过远程调用账户服务来扣减用户账户里面的余额,最后再订单服务中修改订单状态为已完成。
该操作跨越三个数据库,有两次远程调用,很明显有分布式事务问题。
三步走:
- 下订单
- 扣库存
- 减账户余额
4.2 创建业务数据库
- seata_order:存储订单的数据库
- seata_storage:存储库存的数据库
- seata_account:存储账户信息的数据库
建库SQL
CREATE DATABASE seata_order;
CREATE DATABASE seata_storage;
CREATE DATABASE seata_account;
4.3 按照上述3库分别建对应业务表
seata_order库下建t_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;
SELECT * FROM t_order;
seata_storage库下建t_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' );
SELECT * FROM t_storage;
seata_account库下建t_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' );
SELECT * FROM t_account;
4.4 按照上述3库分别建对应的回滚日志
订单-库存-账户三个库下都需要个自己的回滚日志表
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;
4.5 最终效果
5.订单/库存/账户业务微服务准备
5.1 业务需求
- 下订单
- 减库存
- 扣余额
- 改订单状态
5.2 新建Order-Module
5.2.1 新建seata-order-service2001
5.2.2 POM
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.atguigu.springcloud</groupId>
<artifactId>cloud2022</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>seata-order-service2001</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!--分布式事务 -->
<!--移除alibaba-seata自带的seata-spring-boot-starter,因为自带的版本太低 -->
<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>
<exclusion>
<groupId>io.seata</groupId>
<artifactId>seata-all</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--添加seata-spring-boot-starter依赖,版本需要与服务端版本相对应,此版本使用1.5.2 -->
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-spring-boot-starter</artifactId>
<version>1.5.2</version>
</dependency>
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-all</artifactId>
<version>1.5.2</version>
</dependency>
<!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
<dependency>
<groupId>com.atguigu.springcloud</groupId>
<artifactId>cloud-api-common</artifactId>
<version>${project.version}</version>
</dependency>
<!--nacos-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!--feign-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!--web-actuator-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--mysql-druid-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<!--<version>5.1.37</version>-->
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
</project>
seata版本最好要吻合
5.2.3 YML
server:
port: 2001
spring:
application:
name: seata-order-service
cloud:
nacos:
discovery:
server-addr: localhost:8848
namespace: "6f25df50-1e22-4301-9587-d627b6158fc9"
alibaba:
seata:
tx-service-group: fsp_tx_group
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/seata_order
username: root
password: 123456
feign:
hystrix:
enabled: false
logging:
level:
io:
seata: info
mybatis:
mapperLocations: classpath:mapper/*.xml
seata:
tx-service-group: fsp_tx_group #这里每个服务都是对应不同的映射名,在配置中心可以看到
registry:
type: nacos
nacos:
server-addr: localhost:8848
group: SEATA_GROUP
namespace: "6f25df50-1e22-4301-9587-d627b6158fc9"
service:
vgroup-mapping:
#这里也要注意 key为映射名
fsp_tx_group: default
5.2.4 修改seata路径下的/conf/application.yml
server:
port: 7091
spring:
application:
name: seata-server
logging:
config: classpath:logback-spring.xml
file:
path: ${user.home}/logs/seata
extend:
logstash-appender:
destination: 127.0.0.1:4560
kafka-appender:
bootstrap-servers: 127.0.0.1:9092
topic: logback_to_logstash
console:
user:
username: seata
password: seata
seata:
config:
# support: nacos, consul, apollo, zk, etcd3
type: nacos
nacos:
server-addr: http://127.0.0.1:8848
namespace: 6f25df50-1e22-4301-9587-d627b6158fc9
group: SEATA_GROUP
username:
password:
data-id: seataServer.properties
registry:
# support: nacos, eureka, redis, zk, consul, etcd3, sofa
type: nacos
nacos:
application: seata-server
server-addr: http://127.0.0.1:8848
group: SEATA_GROUP
namespace: 6f25df50-1e22-4301-9587-d627b6158fc9
cluster: default #这个还是有必要的,如果不配置的话,微服务一直报error
username:
password:
# store:
# support: file 、 db 、 redis
# mode: file
# server:
# service-port: 8091 #If not configured, the default is '${server.port} + 1000'
security:
secretKey: SeataSecretKey0c382ef121d778043159209298fd40bf3850a017
tokenValidityInMilliseconds: 1800000
ignore:
urls: /,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-fe/public/**,/api/v1/auth/login
5.2.6 遇到的问题和坑
问题1:
i.s.c.r.netty.NettyClientChannelManager:no available server to connect.
查看官方文档:https://github.com/seata/seata-samples/blob/master/doc/quick-integration-with-spring-cloud.md
看到在对 file.conf 的解释说明中提到:
此处一开始没配置,出现这个错误后加上
问题2:
i.s.c.r.netty.NettyClientChannelManager : no available service found in cluster 'DEFAULT', please make sure registry config correct and keep your seata server running
5.2.7 domain
package com.atguigu.springcloud.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 简要描述
*
* @Author: ASuLe
* @Date: 2023/1/21 22:58
* @Version: 1.0
* @Description: 文件作用详细描述....
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CommonResult<T> {
private Integer code;
private String message;
private T data;
public CommonResult(Integer code, String message) {
this(code, message, null);
}
}
package com.atguigu.springcloud.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
/**
* 简要描述
*
* @Author: ASuLe
* @Date: 2023/1/21 22:59
* @Version: 1.0
* @Description: 文件作用详细描述....
*/
@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.2.8 Dao接口及实现
package com.atguigu.springcloud.dao;
import com.atguigu.springcloud.domain.Order;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
/**
* 简要描述
*
* @Author: ASuLe
* @Date: 2023/1/21 23:02
* @Version: 1.0
* @Description: 文件作用详细描述....
*/
@Mapper
public interface OrderDao {
//1.新建订单
void create(Order order);
//2.修改订单状态,从0改为1
void update(@Param("userId") Long userId,@Param("status") Integer status);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.springcloud.dao.OrderDao">
<resultMap id="BaseResultMap" type="com.atguigu.springcloud.domain.Order">
<id 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" parameterType="com.atguigu.springcloud.domain.Order" useGeneratedKeys="true"
keyProperty="id">
insert into t_order(user_id,product_id,count,money,status) values (#{userId},#{productId},#{count},#{money},0);
</insert>
<update id="update">
update t_order set status =1 where user_id =#{userId} and status=#{status};
</update>
</mapper>
5.2.9 Service接口及实现
package com.atguigu.springcloud.service;
import com.atguigu.springcloud.domain.Order;
/**
* 简要描述
*
* @Author: ASuLe
* @Date: 2023/1/21 23:12
* @Version: 1.0
* @Description: 文件作用详细描述....
*/
public interface OrderService {
void create(Order order);
}
package com.atguigu.springcloud.service;
import com.atguigu.springcloud.entities.CommonResult;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.math.BigDecimal;
/**
* 简要描述
*
* @Author: ASuLe
* @Date: 2023/1/21 23:12
* @Version: 1.0
* @Description: 文件作用详细描述....
*/
@FeignClient(value = "seata-account-service")
public interface AccountService {
@PostMapping(value = "/account/decrease")
CommonResult decrease(@RequestParam("userId") Long userId,@RequestParam("money") BigDecimal money);
}
package com.atguigu.springcloud.service;
import com.atguigu.springcloud.entities.CommonResult;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
* 简要描述
*
* @Author: ASuLe
* @Date: 2023/1/21 23:12
* @Version: 1.0
* @Description: 文件作用详细描述....
*/
@FeignClient(value = "seata-storage-service")
public interface StorageService {
@PostMapping(value = "/storage/decrease")
CommonResult decrease(@RequestParam("productId") Long productId,@RequestParam("count") Integer count);
}
package com.atguigu.springcloud.service.impl;
import com.atguigu.springcloud.dao.OrderDao;
import com.atguigu.springcloud.domain.Order;
import com.atguigu.springcloud.service.AccountService;
import com.atguigu.springcloud.service.OrderService;
import com.atguigu.springcloud.service.StorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* 简要描述
*
* @Author: ASuLe
* @Date: 2023/1/21 23:13
* @Version: 1.0
* @Description: 文件作用详细描述....
*/
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
@Resource
private OrderDao orderDao;
@Resource
private StorageService storageService;
@Resource
private AccountService accountService;
@Override
public void create(Order order) {
log.info("-------------->开始新建订单");
//1.新建订单
orderDao.create(order);
log.info("-------------->订单微服务开始调用库存,做扣减Count");
//2.扣减库存
storageService.decrease(order.getProductId(), order.getCount());
log.info("-------------->订单微服务开始调用库存,做扣减end");
log.info("-------------->订单微服务开始调用账户,做扣减Money");
//3.扣减账户
accountService.decrease(order.getUserId(), order.getMoney());
log.info("-------------->订单微服务开始调用账户,做扣减end");
//4.修改订单状态,从0到1,1代表已经完成
log.info("-------------->修改订单状态开始");
//要把某个用户的状态从0改为1
orderDao.update(order.getUserId(), 0);
log.info("-------------->修改订单状态结束");
log.info("-------------->下订单结束了,O(∩_∩)O~");
}
}
5.2.10 Conrtoller
package com.atguigu.springcloud.controller;
import com.atguigu.springcloud.domain.Order;
import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.service.OrderService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* 简要描述
*
* @Author: ASuLe
* @Date: 2023/1/21 23:27
* @Version: 1.0
* @Description: 文件作用详细描述....
*/
@RestController
public class OrderController {
@Resource
private OrderService orderService;
@GetMapping("/order/create")
public CommonResult create(Order order){
orderService.create(order);
return new CommonResult(200,"订单创建成功");
}
}
5.2.10 Config配置
package com.atguigu.springcloud.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
/**
* 简要描述
*
* @Author: ASuLe
* @Date: 2023/1/24 10:09
* @Version: 1.0
* @Description: 文件作用详细描述....
*/
@Configuration
@Data
public class DataSourceConfig {
@Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.username}")
private String userName;
@Value("${spring.datasource.password}")
private String password;
@Value("${spring.datasource.driver-class-name}")
private String driveClassName;
}
package com.atguigu.springcloud.config;
import com.zaxxer.hikari.HikariDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
/**
* 简要描述
*
* @Author: ASuLe
* @Date: 2023/1/24 10:09
* @Version: 1.0
* @Description: 文件作用详细描述....
*/
@Configuration
public class DataSourceProxyConfig {
@Autowired
private DataSourceConfig dataSourceConfig;
@Bean("dataSource")
public DataSource druidDataSource() {
HikariDataSource hikariDataSource = new HikariDataSource();
hikariDataSource.setJdbcUrl(dataSourceConfig.getUrl());
hikariDataSource.setUsername(dataSourceConfig.getUserName());
hikariDataSource.setPassword(dataSourceConfig.getPassword());
hikariDataSource.setDriverClassName(dataSourceConfig.getDriveClassName());
return hikariDataSource;
}
@Bean
@Primary
public DataSourceProxy dataSourceProxy(DataSource dataSource) {
return new DataSourceProxy(dataSource);
}
}
5.2.11 主启动
package com.atguigu.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
/**
* 简要描述
*
* @Author: ASuLe
* @Date: ${DATE} ${TIME}
* @Version: 1.0
* @Description: 文件作用详细描述....
*/
@EnableDiscoveryClient
@EnableFeignClients
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class SeataAccountApplication2003 {
public static void main(String[] args) {
SpringApplication.run(SeataAccountApplication2003.class, args);
}
}
5.3 新建Storage-Module
5.3.1 新建seata-storage-service2002
5.3.2 POM
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.atguigu.springcloud</groupId>
<artifactId>cloud2022</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>seata-storage-service2002</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!--分布式事务 -->
<!--移除alibaba-seata自带的seata-spring-boot-starter,因为自带的版本太低 -->
<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>
<exclusion>
<groupId>io.seata</groupId>
<artifactId>seata-all</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--添加seata-spring-boot-starter依赖,版本需要与服务端版本相对应,此版本使用1.5.2 -->
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-spring-boot-starter</artifactId>
<version>1.5.2</version>
</dependency>
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-all</artifactId>
<version>1.5.2</version>
</dependency>
<!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
<dependency>
<groupId>com.atguigu.springcloud</groupId>
<artifactId>cloud-api-common</artifactId>
<version>${project.version}</version>
</dependency>
<!--nacos-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!--feign-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!--web-actuator-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--mysql-druid-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<!--<version>5.1.37</version>-->
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
</project>
5.3.3 YML
server:
port: 2002
spring:
application:
name: seata-storage-service
cloud:
nacos:
discovery:
server-addr: localhost:8848
namespace: "6f25df50-1e22-4301-9587-d627b6158fc9"
alibaba:
seata:
tx-service-group: fsp_tx_group
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/seata_storage
username: root
password: 123456
feign:
hystrix:
enabled: false
logging:
level:
io:
seata: info
mybatis:
mapperLocations: classpath:mapper/*.xml
seata:
tx-service-group: fsp_tx_group #这里每个服务都是对应不同的映射名,在配置中心可以看到
registry:
type: nacos
nacos:
server-addr: localhost:8848
group: SEATA_GROUP
namespace: "6f25df50-1e22-4301-9587-d627b6158fc9"
service:
vgroup-mapping:
#这里也要注意 key为映射名
fsp_tx_group: default
5.3.4 修改seata路径下的/conf/application.yml
2001中已经配置过了
5.3.5 domain
package com.atguigu.springcloud.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 简要描述
*
* @Author: ASuLe
* @Date: 2023/1/21 22:58
* @Version: 1.0
* @Description: 文件作用详细描述....
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CommonResult<T> {
private Integer code;
private String message;
private T data;
public CommonResult(Integer code, String message) {
this(code, message, null);
}
}
package com.atguigu.springcloud.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 简要描述
*
* @Author: ASuLe
* @Date: 2023/1/23 14:31
* @Version: 1.0
* @Description: 文件作用详细描述....
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Storage {
private Long id;
/**
* 产品id
*/
private Long productId;
/**
* 总库存
*/
private Integer total;
/**
* 已用库存
*/
private Integer used;
/**
* 剩余库存
*/
private Integer residue;
}
5.3.6 Dao接口及实现
package com.atguigu.springcloud.dao;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
/**
* 简要描述
*
* @Author: ASuLe
* @Date: 2023/1/23 14:32
* @Version: 1.0
* @Description: 文件作用详细描述....
*/
@Mapper
public interface StorageDao {
/**
* 减库存
* @param productId
* @param count
* @return
*/
void decrease(@Param("productId") Long productId, @Param("count") Integer count);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.springcloud.dao.StorageDao">
<resultMap id="BaseResultMap" type="com.atguigu.springcloud.domain.Storage">
<id column="id" property="id" jdbcType="BIGINT"></id>
<result column="product_id" property="productId" jdbcType="BIGINT"></result>
<result column="total" property="total" jdbcType="INTEGER"></result>
<result column="used" property="used" jdbcType="INTEGER"></result>
<result column="residue" property="residue" jdbcType="INTEGER"></result>
</resultMap>
<!--减库存-->
<update id="decrease">
update t_storage
set used =used + #{count},
residue=residue - #{count}
where product_id = #{productId};
</update>
</mapper>
5.3.7 Service接口及实现
package com.atguigu.springcloud.service;
/**
* 简要描述
*
* @Author: ASuLe
* @Date: 2023/1/23 14:35
* @Version: 1.0
* @Description: 文件作用详细描述....
*/
public interface StorageService {
void decrease(Long productId, Integer count);
}
package com.atguigu.springcloud.service.impl;
import com.atguigu.springcloud.dao.StorageDao;
import com.atguigu.springcloud.service.StorageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* 简要描述
*
* @Author: ASuLe
* @Date: 2023/1/23 14:36
* @Version: 1.0
* @Description: 文件作用详细描述....
*/
@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中扣减库存结束");
}
}
5.3.8 Conrtoller
package com.atguigu.springcloud.controller;
import com.atguigu.springcloud.domain.CommonResult;
import com.atguigu.springcloud.service.StorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* 简要描述
*
* @Author: ASuLe
* @Date: 2023/1/23 14:39
* @Version: 1.0
* @Description: 文件作用详细描述....
*/
@RestController
public class StorageController {
@Autowired
private StorageService storageService;
/**
* 减库存
*
* @param productId
* @param count
* @return
*/
@PostMapping(value = "/storage/decrease")
public CommonResult decrease(@RequestParam("productId") Long productId, @RequestParam("count") Integer count) {
storageService.decrease(productId, count);
return new CommonResult(200, "扣减库存成功");
}
}
5.3.9 Config配置
package com.atguigu.springcloud.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
/**
* 简要描述
*
* @Author: ASuLe
* @Date: 2023/1/24 10:09
* @Version: 1.0
* @Description: 文件作用详细描述....
*/
@Configuration
@Data
public class DataSourceConfig {
@Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.username}")
private String userName;
@Value("${spring.datasource.password}")
private String password;
@Value("${spring.datasource.driver-class-name}")
private String driveClassName;
}
package com.atguigu.springcloud.config;
import com.zaxxer.hikari.HikariDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
/**
* 简要描述
*
* @Author: ASuLe
* @Date: 2023/1/24 10:09
* @Version: 1.0
* @Description: 文件作用详细描述....
*/
@Configuration
public class DataSourceProxyConfig {
@Autowired
private DataSourceConfig dataSourceConfig;
@Bean("dataSource")
public DataSource druidDataSource() {
HikariDataSource hikariDataSource = new HikariDataSource();
hikariDataSource.setJdbcUrl(dataSourceConfig.getUrl());
hikariDataSource.setUsername(dataSourceConfig.getUserName());
hikariDataSource.setPassword(dataSourceConfig.getPassword());
hikariDataSource.setDriverClassName(dataSourceConfig.getDriveClassName());
return hikariDataSource;
}
@Bean
@Primary
public DataSourceProxy dataSourceProxy(DataSource dataSource) {
return new DataSourceProxy(dataSource);
}
}
5.3.10 主启动
package com.atguigu.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
/**
* 简要描述
*
* @Author: ASuLe
* @Date: ${DATE} ${TIME}
* @Version: 1.0
* @Description: 文件作用详细描述....
*/
@EnableDiscoveryClient
@EnableFeignClients
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class SeataStorageServiceApplication2002 {
public static void main(String[] args) {
SpringApplication.run(SeataStorageServiceApplication2002.class, args);
}
}
5.4 新建Account-Module
5.4.1 新建seata-account-service2003
5.4.2 POM
5.4.3 YML
5.4.4 修改seata路径下的/conf/application.yml
5.4.5 domain
5.4.6 Dao接口及实现
5.4.7 Service接口及实现
5.4.8 Conrtoller
5.4.9 Config配置
package com.atguigu.springcloud.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
/**
* 简要描述
*
* @Author: ASuLe
* @Date: 2023/1/24 10:09
* @Version: 1.0
* @Description: 文件作用详细描述....
*/
@Configuration
@Data
public class DataSourceConfig {
@Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.username}")
private String userName;
@Value("${spring.datasource.password}")
private String password;
@Value("${spring.datasource.driver-class-name}")
private String driveClassName;
}
package com.atguigu.springcloud.config;
import com.zaxxer.hikari.HikariDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
/**
* 简要描述
*
* @Author: ASuLe
* @Date: 2023/1/24 10:09
* @Version: 1.0
* @Description: 文件作用详细描述....
*/
@Configuration
public class DataSourceProxyConfig {
@Autowired
private DataSourceConfig dataSourceConfig;
@Bean("dataSource")
public DataSource druidDataSource() {
HikariDataSource hikariDataSource = new HikariDataSource();
hikariDataSource.setJdbcUrl(dataSourceConfig.getUrl());
hikariDataSource.setUsername(dataSourceConfig.getUserName());
hikariDataSource.setPassword(dataSourceConfig.getPassword());
hikariDataSource.setDriverClassName(dataSourceConfig.getDriveClassName());
return hikariDataSource;
}
@Bean
@Primary
public DataSourceProxy dataSourceProxy(DataSource dataSource) {
return new DataSourceProxy(dataSource);
}
}
5.4.10 主启动
package com.atguigu.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
/**
* 简要描述
*
* @Author: ASuLe
* @Date: ${DATE} ${TIME}
* @Version: 1.0
* @Description: 文件作用详细描述....
*/
@EnableDiscoveryClient
@EnableFeignClients
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class SeataAccountApplication2003 {
public static void main(String[] args) {
SpringApplication.run(SeataAccountApplication2003.class, args);
}
}
6.测试
6.1数据库初始情况
6.2 正常下单
测试地址: http://localhost:2001/order/create?userId=1&productId=1&count=10&money=100
6.3 超时异常,没加@GlobalTransactional
在2003的AccountS中模拟超时异常
在此处睡20秒,OpenFeign的调用默认时间是1秒钟,现在睡20秒肯定报超时异常
故障情况:
- 当库存和账户金额扣减后,订单状态没有设置为已完成,没有从0改为1
- 而且由于feign重试机制,账户余额还有可能被多次扣减
6.4 超时异常,添加@GlobalTransactional
业务入口2001的OrderServiceImpl上添加@GlobalTransactional
7.补充
7.1 Seata
2019年1月蚂蚁金服和阿里巴巴共同开源的分布式事务解决方案
Simple Extensible Autonomous Transaction Architecture,简单可扩展自治事务框架
2020年起始,参加工作后用1.0以后的版本
7.2 再看TC/TM/RM三大组件
分布式事务的执行流程:
- TM开启分布式事务(TM向TC注册全局事务记录)
- 按业务场景,编排数据库、服务等事务内资源(RM向TC汇报资源状态)
- TM结束分布式事务,事务一阶段结束(TM通知TC提交/回滚分布式事务)
- TC汇总事务信息,决定分布式事务是提交还是回滚
- TC通知所有RM提交/回滚资源,事务二阶段结束。
7.3 AT模式如何做到对业务的无侵入
7.3.1 是什么
7.3.2 一阶段加载
在一阶段,Seata会拦截"业务SQL"
- 解析SQL语义,找到"业务SQL"要更新的业务数据,在业务数据被更新前,将其保存成"before image"
- 执行"业务SQL"更新业务数据
- 在业务数据更新之后,将其保存成"after image",最后生产行锁
以上操作全部在一个数据库事务内完成,这样保证了一阶段操作的原子性
7.3.3 正常情况二阶段提交
二阶段如果顺利提交的话,因为"业务SQL"在一阶段已经提交至数据库,所以Seata框架只需将一阶段保存的快照数据和行锁删掉,完成数据清理即可。
7.3.4 异常情况二阶段回滚
二阶段如果是回滚的话,Seata就需要回滚一阶段已经执行的"业务SQL",还原业务数据。
回滚方式便是使用"before image"还原业务数据;但在还原前首先要校验脏写,对比"数据库当前业务数据"和"after image",如果两份数据完全一致就说明没有脏写,可以还原业务数据,如果不一致就说明有脏写,出现脏写就需要转人工处理。
7.4 debug
修改2003的AccountServiceImpl
debug运行,测试地址,观察seata库
在undo_log表的rollback_info都有记录
如果成功了那就没问题,如果失败了就反补,就是把修改的数据根据before image(记录了修改之前的值和修改之后的值)回退到原始的数据状态,还原前首先要校验脏写,如果高并发条件下,28改成了32,别人已经在我之前动过这个数据了,我就改不回去了,类似于乐观锁
这几张表都锁了