1 Seata介绍
Seata是由阿里中间件团队发起的开源分布式事务框架项目,
依赖支持本地 ACID 事务的关系型数据库,
可以高效并且对业务0侵入的方式解决微服务场景下面临的分布式事务问题,
目前提供AT模式(即2PC)、TCC、SAGA 和 XA 的分布式事务解决方案。
2 Seata的设计思想
Seata的设计目标其一是对业务无侵入,因此从业务无侵入的2PC方案着手,在传统2PC的基础上演进,并解决2PC方案面临的刚性事务问题。
2.1 Seata术语&实现原理
TC (Transaction Coordinator) - 事务协调者
它是独立的中间件,需要独立部署运行,它维护全局事务的运行状态,接收TM指令发起全局事务的提交与回滚,
负责与RM通信协调各各分支事务的提交或回滚。
TM (Transaction Manager) - 事务管理器 - 事务发起者
TM需要嵌入应用程序中工作,它负责开启一个全局事务,并最终向TC发起全局提交或全局回滚的指令。
RM (Resource Manager) - 资源管理器 - 事务参与者
控制分支事务,负责分支注册、状态汇报,并接收事务协调器TC的指令,驱动分支(本地)事务的提交和回滚。
2.2 AT模式 工作机制
首先:AT模式是由2PC演变而来,在2PC的基础上增加了数据镜像(undolog表)的功能来实现分布式事务的回滚。
流程:
TM要求TC开始一项新的事务分支。TC生成代表全局事务的XID返回给TM。
TM请求其它服务时携带XID参数通过微服务的调用链传播。
RM将本地事务注册为XID到TC的相应全局事务的分支。
TM要求TC提交或回滚XID的相应全局事务。
TC驱动XID对应的全局事务下的所有分支事务以完成分支提交或回滚。
如果需要回滚的话,需要用到“undolog回滚日志”表进行回滚操作。
2.3 undolog回滚日志表详解(前置、后置镜像)
案例:
1、user业务表
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into user values(1, "王明", 19);
insert into user values(1, "王亮", 10);
2、执行业务SQL:update user set age = 20 where name = “王明”;
3、Seata会拦截该业务SQL,对该SQL添加前置镜像、后置镜像并将前置、后置镜像得到的数据记录到undolog表中:
前置镜像:业务SQL修改之前的数据;
后置镜像:业务SQL修改之后的数据。
前置镜像:select id, name, age from user where name = “王明”;
业务SQL:update user set age = 20 where name = “王明”;
后置镜像:select id, name, age from user where id = #{前置镜像得到的主键id};
前置镜像的到的数据:
后置镜像得到的数据:
4、如果执行回滚操作,则根据XID读取undolog表中的前置镜像和业务SQL信息,并生成回滚SQL语句执行:
生成的回滚SQL语句:update user set age = 19 where id = 1;
5、如果执行提交,则直接把undolog表中,相关镜像删除即可。
3 Seata环境搭建
3.1 Seata服务器搭建
本次实践为seata最新版本为v1.5.1,
下载地址
http://seata.io/zh-cn/blog/download.html,下载下来进行解压,目录结构如下:
3.1.1 Seata简单安装 - 单机
进入bin目录直接启动seata,
seata服务默认端口是8091、客户端端口7091
window下双击运行seata-server.bat
linux下运行seata-server.sh
输出以下信息表示启动成功,默认Seata服务端口8091
4.1.1 seata高可用安装 - 集成Nacos、DB
Seata服务端支持三种存储模式(store.mode):
file:单机模式,全局事务会话信息内存中读写并持久化本地文件root.data,性能较高
db:高可用模式,全局事务会话信息通过db共享,相应性能差些
redis:Seata-Server 1.3及以上版本支持,性能较高,存在事务信息丢失风险,请提前配置适合当前场景的redis持久化配置
4.1.2 创建Seata依赖的数据库实例
新建一个seata数据库实例,然后导入以下SQL,或者导入学习资料中提供的seata.sql。
注意:seata数据库字符集需要是utf8mb4 -- UTF-8 Unicode
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for branch_table
-- ----------------------------
DROP TABLE IF EXISTS `branch_table`;
CREATE TABLE `branch_table` (
`branch_id` bigint(20) NOT NULL,
`xid` varchar(128) NOT NULL,
`transaction_id` bigint(20) DEFAULT NULL,
`resource_group_id` varchar(32) DEFAULT NULL,
`resource_id` varchar(256) DEFAULT NULL,
`branch_type` varchar(8) DEFAULT NULL,
`status` tinyint(4) DEFAULT NULL,
`client_id` varchar(64) DEFAULT NULL,
`application_data` varchar(2000) DEFAULT NULL,
`gmt_create` datetime(6) DEFAULT NULL,
`gmt_modified` datetime(6) DEFAULT NULL,
PRIMARY KEY (`branch_id`),
KEY `idx_xid` (`xid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of branch_table
-- ----------------------------
-- ----------------------------
-- Table structure for distributed_lock
-- ----------------------------
DROP TABLE IF EXISTS `distributed_lock`;
CREATE TABLE `distributed_lock` (
`lock_key` char(20) NOT NULL,
`lock_value` varchar(20) NOT NULL,
`expire` bigint(20) DEFAULT NULL,
PRIMARY KEY (`lock_key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of distributed_lock
-- ----------------------------
INSERT INTO `distributed_lock` VALUES ('AsyncCommitting', ' ', '0');
INSERT INTO `distributed_lock` VALUES ('RetryCommitting', ' ', '0');
INSERT INTO `distributed_lock` VALUES ('RetryRollbacking', ' ', '0');
INSERT INTO `distributed_lock` VALUES ('TxTimeoutCheck', ' ', '0');
-- ----------------------------
-- Table structure for global_table
-- ----------------------------
DROP TABLE IF EXISTS `global_table`;
CREATE TABLE `global_table` (
`xid` varchar(128) NOT NULL,
`transaction_id` bigint(20) DEFAULT NULL,
`status` tinyint(4) NOT NULL,
`application_id` varchar(32) DEFAULT NULL,
`transaction_service_group` varchar(32) DEFAULT NULL,
`transaction_name` varchar(128) DEFAULT NULL,
`timeout` int(11) DEFAULT NULL,
`begin_time` bigint(20) DEFAULT NULL,
`application_data` varchar(2000) DEFAULT NULL,
`gmt_create` datetime DEFAULT NULL,
`gmt_modified` datetime DEFAULT NULL,
PRIMARY KEY (`xid`),
KEY `idx_status_gmt_modified` (`status`,`gmt_modified`),
KEY `idx_transaction_id` (`transaction_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of global_table
-- ----------------------------
-- ----------------------------
-- Table structure for lock_table
-- ----------------------------
DROP TABLE IF EXISTS `lock_table`;
CREATE TABLE `lock_table` (
`row_key` varchar(128) NOT NULL,
`xid` varchar(128) DEFAULT NULL,
`transaction_id` bigint(20) DEFAULT NULL,
`branch_id` bigint(20) NOT NULL,
`resource_id` varchar(256) DEFAULT NULL,
`table_name` varchar(32) DEFAULT NULL,
`pk` varchar(36) DEFAULT NULL,
`status` tinyint(4) NOT NULL DEFAULT '0' COMMENT '0:locked ,1:rollbacking',
`gmt_create` datetime DEFAULT NULL,
`gmt_modified` datetime DEFAULT NULL,
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;
4.1.2 启动nacos
可以使用资料中的nacos-2.4.5.jar文件,通过java -jar nacos-2.4.5.jar的方式启动nacos服务,启动nacos前需要修改数据源地址。
学习资料中提供了nacos依赖的数据库SQL文件:nacos.sql
资料下载地址:
https://pan.baidu.com/s/16YFbXeRpOzNWIO_jhyH0-g?pwd=1bvd
4.1.3 在nacos配置中心添加Seata配置seataServer.properties
Data ID: seataServer.properties
Group: SEATA_GROUP
添加seataServer.properties内容,需要自行修改seata数据库连接。
service.vgroupMapping.default-tx-group=default
service.default.grouplist=127.0.0.1:8091
service.enableDegrade=false
service.disableGlobalTransaction=false
store.mode=db
store.db.datasource=druid
store.db.dbType=mysql
store.db.driverClassName=com.mysql.jdbc.Driver
store.db.url=jdbc:mysql://127.0.0.1:3306/seata?useUnicode=true
store.db.user=root
store.db.password=root
store.db.minConn=5
store.db.maxConn=30
store.db.globalTable=global_table
store.db.branchTable=branch_table
store.db.queryLimit=100
store.db.lockTable=lock_table
store.db.maxWait=5000
4.1.4 修改Seata配置文件application.yml
修改seata-server-1.5.1\seata\conf\application.yml配置文件,修改config、registry的type值为nacos
注意:如果使用了Nacos作为配置中心,那么就不需要在该配置文件中配置store,Seata会从Nacos配置中心读取。
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: 127.0.0.1:8848
namespace:
group: SEATA_GROUP
username: nacos
password: nacos
##if use MSE Nacos with auth, mutex with username/password attribute
#access-key: ""
#secret-key: ""
data-id: seataServer.properties
registry:
# support: nacos, eureka, redis, zk, consul, etcd3, sofa
type: nacos
nacos:
application: seata-server
server-addr: 127.0.0.1:8848
group: SEATA_GROUP
namespace:
cluster: default
username: nacos
password: nacos
# store:
# support: file 、 db 、 redis
# mode: db
# db:
# datasource: druid
# db-type: mysql
# driver-class-name: com.mysql.jdbc.Driver
# url: jdbc:mysql://${MY_MYSQL_URL}/seata?rewriteBatchedStatements=true
# user: ${MY_MYSQL_USERNAME}
# password: ${MY_MYSQL_PASSWORD}
# min-conn: 5
# max-conn: 100
# global-table: global_table
# branch-table: branch_table
# lock-table: lock_table
# distributed-lock-table: distributed_lock
# query-limit: 100
# max-wait: 5000
# 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
4.1.5 启动Seata服务
进入bin目录启动Seata,Seata服务默认端口是8091、客户端端口7091
window下双击运行seata-server.bat
linux下运行seata-server.sh
5.1 Seata客户端搭建
5.1.1 在业务数据库中需要加入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=19 DEFAULT CHARSET=utf8;
5.1.2 Seata依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-seata</artifactId>
<version>2.2.3.RELEASE</version>
</dependency>
5.1.3 application.yml配置
server:
port: 8080
spring:
application:
name: kexuekt-mamber
datasource:
url: jdbc:mysql://${MY_MYSQL_URL}/mamber?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT
username: ${MY_MYSQL_USERNAME}
password: ${MY_MYSQL_PASSWORD}
driver-class-name: com.mysql.jdbc.Driver
seata:
enabled: true
enable-auto-data-source-proxy: true
tx-service-group: default-tx-group
service:
vgroup-mapping:
default-tx-group: default
disable-global-transaction: false
client:
rm:
report-success-enable: false
注意: