当前位置:网站首页>Seata分布式事务
Seata分布式事务
2022-08-02 12:49:00 【bluepad】
CAP原则
CAP原则又称CAP定理,指的是在一个分布式系统中,一致性(Consistency)、可用性(Availability)、分区容错性(Partition tolerance)。CAP 原则指的是,这三个要素最多只能同时实现两点,不可能三者兼顾。
分区性:
数据一致性
分布式事务协议——2PC
假设没有错误情况下:
假设其中某一参与者出错:
不管最后结果如何,第二阶段都会结束当前事务
分布式事务协议——3PC
Seata
seata术语
seata有四种模式:AT、TCC、Sage、XA,其中AT模式是最常用的模式
详情参见https://www.pianshen.com/article/34341263271/
AT模式具体实现步骤
实现步骤:
- TM端使用@GolableTranscation进行全局事务开启、提交、回滚
- TM开始RPC调用远程服务
- RM端seata-client通过扩展DataSourceProxy,实现自动生成undo-log与TC上报
- TM告知TC提交/回滚全局事务
- TC通知RM各自执行commit/rollback操作,同时清除undo-log
win10启动seata,需要64位java8,如遇闪退情况需检查此问题
1.seata 数据源配置
下载seata程序包,此处版本为1.3.0
修改配置文件E:softseataseataconf ile.conf
## transaction log store, only used in seata-server
store {
## store mode: file、db、redis
mode = "db"
## file store property
file {
## store location dir
dir = "sessionStore"
# branch session size , if exceeded first try compress lockkey, still exceeded throws exceptions
maxBranchSessionSize = 16384
# globe session size , if exceeded throws exceptions
maxGlobalSessionSize = 512
# file buffer size , if exceeded allocate new buffer
fileWriteBufferCacheSize = 16384
# when recover batch read size
sessionReloadReadSize = 100
# async, sync
flushDiskMode = async
}
## database store property
db {
## the implement of javax.sql.DataSource, such as DruidDataSource(druid)/BasicDataSource(dbcp)/HikariDataSource(hikari) etc.
datasource = "druid"
## mysql/oracle/postgresql/h2/oceanbase etc.
dbType = "mysql"
driverClassName = "com.mysql.cj.jdbc.Driver"
url = "jdbc:mysql://host:3306/seata?characterEncoding=UTF-8&useUnicode=true&useSSL=false&tinyInt1isBit=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai"
user = "root"
password = "xxx"
minConn = 5
maxConn = 30
globalTable = "global_table"
branchTable = "branch_table"
lockTable = "lock_table"
queryLimit = 100
maxWait = 5000
}
## redis store property
redis {
host = "47.100.42.118"
port = "6379"
password = ""
database = "0"
minConn = 1
maxConn = 10
queryLimit = 100
}
}
此处修改默认配置为:seata数据源类型为db,并配置mysql数据源
如果用mysql作为数据源,需要初始化SQL建表,下面贴出:
DROP TABLE IF EXISTS `branch_table`;
CREATE TABLE `branch_table` (
`branch_id` bigint(20) NOT NULL,
`xid` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`transaction_id` bigint(20) NULL DEFAULT NULL,
`resource_group_id` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`resource_id` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`branch_type` varchar(8) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`status` tinyint(4) NULL DEFAULT NULL,
`client_id` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`application_data` varchar(2000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`gmt_create` datetime(0) NULL DEFAULT NULL,
`gmt_modified` datetime(0) NULL DEFAULT NULL,
PRIMARY KEY (`branch_id`) USING BTREE,
INDEX `idx_xid`(`xid`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for global_table
-- ----------------------------
DROP TABLE IF EXISTS `global_table`;
CREATE TABLE `global_table` (
`xid` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`transaction_id` bigint(20) NULL DEFAULT NULL,
`status` tinyint(4) NOT NULL,
`application_id` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`transaction_service_group` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`transaction_name` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`timeout` int(11) NULL DEFAULT NULL,
`begin_time` bigint(20) NULL DEFAULT NULL,
`application_data` varchar(2000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`gmt_create` datetime(0) NULL DEFAULT NULL,
`gmt_modified` datetime(0) NULL DEFAULT NULL,
PRIMARY KEY (`xid`) USING BTREE,
INDEX `idx_gmt_modified_status`(`gmt_modified`, `status`) USING BTREE,
INDEX `idx_transaction_id`(`transaction_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for lock_table
-- ----------------------------
DROP TABLE IF EXISTS `lock_table`;
CREATE TABLE `lock_table` (
`row_key` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`xid` varchar(96) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`transaction_id` bigint(20) NULL DEFAULT NULL,
`branch_id` bigint(20) NOT NULL,
`resource_id` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`table_name` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`pk` varchar(36) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`gmt_create` datetime(0) NULL DEFAULT NULL,
`gmt_modified` datetime(0) NULL DEFAULT NULL,
PRIMARY KEY (`row_key`) USING BTREE,
INDEX `idx_branch_id`(`branch_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
2.seata 注册配置
编辑E:softseataseataconf egistory.conf
registry {
# file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
type = "nacos"
nacos {
application = "seata-server"
serverAddr = "127.0.0.1:8848"
# group = "test"
namespace = "fcf48d9c-1b25-413a-b365-2fa20ad3568d"
cluster = "default"
username = ""
password = ""
}
eureka {
serviceUrl = "http://localhost:8761/eureka"
application = "default"
weight = "1"
}
redis {
serverAddr = "localhost:6379"
db = 0
password = ""
cluster = "default"
timeout = 0
}
zk {
cluster = "default"
serverAddr = "127.0.0.1:2181"
sessionTimeout = 6000
connectTimeout = 2000
username = ""
password = ""
}
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 = "nacos"
nacos {
serverAddr = "localhost"
namespace = "fcf48d9c-1b25-413a-b365-2fa20ad3568d"
group = "SEATA_GROUP"
username = "nacos"
password = "nacos"
}
consul {
serverAddr = "127.0.0.1:8500"
}
apollo {
appId = "seata-server"
apolloMeta = "http://192.168.1.204:8801"
namespace = "application"
}
zk {
serverAddr = "127.0.0.1:2181"
sessionTimeout = 6000
connectTimeout = 2000
username = ""
password = ""
}
etcd3 {
serverAddr = "http://localhost:2379"
}
file {
name = "file.conf"
}
}
3.推送详细配置到nacos
进入nacos项目地址,下载配置文件,或复制粘贴到本地
https://github.com/seata/seata/tree/1.3.0/script/config-center
在seata/script/config-center/中找到config.txt文件
在seata/script/config-center/nacos/中找到nacos-config.sh脚本
下载完成后config.txt放在bin同级目录下,bin同级目录下新建script文件夹,将sh脚本放入其中
进入script目录,cmd:启动脚本
sh nacos-config.sh -h localhost -p 8848 -t fcf48d9c-1b25-413a-b365-2fa20ad3568d -g STATE_GROUP -u nacos -w nacos
-h: nacos地址
-p: nacos端口
-t: 命名空间id
-g: 组名
-u -w: nacos账户名密码
在nacos上对应命名空间查看配置文件是否上传成功
4.启动seata
进入目录 E:softseataseatain 启动seata-server.bat,如遇闪退,可以在cmd命令行中执行bat启动程序,这种方式可以查看错误日志
创建一个RM
引入依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-seata</artifactId>
</dependency>
seata配置
seata:
application-id: seata-server
tx-service-group: my_test_tx_group
config:
type: nacos
nacos:
namespace: fcf48d9c-1b25-413a-b365-2fa20ad3568d
server-addr: localhost:8848
group: STATE_GROUP
username: "nacos"
password: "nacos"
registry:
type: nacos
nacos:
application: seata-server
server-addr: localhost:8848
# group:
namespace: fcf48d9c-1b25-413a-b365-2fa20ad3568d
username: "nacos"
password: "nacos"
RM的业务代码与其他普通项目并无区别…
创建一个TC
同样引入pom依赖、做好seata配置,与RM无异
@GlobalTransactional
public String deleteUser(){
//微服务1
userService.selectUser();
//微服务2
userService.delUser();
int i = userMapper.deleteById("1");
return i==1?"删除成功":"删除失败";
}
通过@GlobalTransactional注解进行全局事务管理,微服务一方失败都会导致全局回滚
password: "nacos"
RM的业务代码与其他普通项目并无区别......
## 创建一个TC
同样引入pom依赖、做好seata配置,与RM无异
```java
@GlobalTransactional
public String deleteUser(){
//微服务1
userService.selectUser();
//微服务2
userService.delUser();
int i = userMapper.deleteById("1");
return i==1?"删除成功":"删除失败";
}
通过@GlobalTransactional注解进行全局事务管理,微服务一方失败都会导致全局回滚
先自我介绍一下,小编13年上师交大毕业,曾经在小公司待过,去过华为OPPO等大厂,18年进入阿里,直到现在。深知大多数初中级java工程师,想要升技能,往往是需要自己摸索成长或是报班学习,但对于培训机构动则近万元的学费,着实压力不小。自己不成体系的自学效率很低又漫长,而且容易碰到天花板技术停止不前。因此我收集了一份《java开发全套学习资料》送给大家,初衷也很简单,就是希望帮助到想自学又不知道该从何学起的朋友,同时减轻大家的负担。添加下方名片,即可获取全套学习资料哦
边栏推荐
猜你喜欢
随机推荐
智能手表前景如何?
图论之Floyd,多源图最短路如何暴力美学?
FreeRTOS实验--一个函数创建多个任务
LeetCode_377_Combination Sum IV
路由-嵌套路由
SQL Server修改数据
js cool dashboard plugin
数据湖(二):什么是Hudi
PHP+MYSQL [Student Information Management System] (Minimalist Edition)
php - the first of three solid foundations
package.json与package-lock.json
zabbix automated monitoring script
如何关闭开启硬件加速[通俗易懂]
OpenFeign设置header的3种方式
pytorch模型转tensorflow模型
Interpretation of new features | MySQL 8.0 GIPK invisible primary key
1.3快速生成树协议RSTP
Set proxy server (Google+IE) "Recommended Collection"
Pod Scheduling Strategy: Affinity, Stain and Stain Tolerance
SQL Server 数据库之导入导出数据