当前位置:网站首页>Seata Distributed Transaction
Seata Distributed Transaction
2022-08-02 12:59:00 【bluepad】
CAP原则
CAP原则又称CAP定理,指的是在一个分布式系统中,一致性(Consistency)、可用性(Availability)、分区容错性(Partition tolerance).CAP 原则指的是,这三个要素最多只能同时实现两点,不可能三者兼顾.

分区性:

数据一致性




分布式事务协议——2PC

Assuming no error conditions:

Suppose one of the participants made a mistake:


不管最后结果如何,第二阶段都会结束当前事务

分布式事务协议——3PC

Seata
seata术语
seata有四种模式:AT、TCC、Sage、XA,其中ATMode is the most commonly used mode
详情参见https://www.pianshen.com/article/34341263271/

ATMode specific implementation steps

实现步骤:
- TM端使用@GolableTranscation进行全局事务开启、提交、回滚
- TM开始RPC调用远程服务
- RM端seata-client通过扩展DataSourceProxy,实现自动生成undo-log与TC上报
- TM告知TC提交/回滚全局事务
- TC通知RM各自执行commit/rollback操作,同时清除undo-log
win10启动seata,需要64位java8,In case of crash, please check this problem
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
}
}
The default configuration is modified here: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.Push detailed configuration tonacos
进入nacos项目地址,下载配置文件,Or copy and paste it locally
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文件夹,将shscript into it
进入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账户名密码
在nacosGo to the corresponding namespace to check whether the configuration file is uploaded successfully
4.启动seata
进入目录 E:softseataseatain 启动seata-server.bat,In case of flashback,可以在cmd命令行中执行bat启动程序,This way you can view the error log
创建一个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"
RMThe business code is no different from other ordinary projects…
创建一个TC
同样引入pom依赖、做好seata配置,与RM无异
@GlobalTransactional
public String deleteUser(){
//微服务1
userService.selectUser();
//微服务2
userService.delUser();
int i = userMapper.deleteById("1");
return i==1?"删除成功":"删除失败";
}
通过@GlobalTransactionalAnnotations perform global transaction management,Failure on one side of the microservice will result in a global rollback
password: "nacos"
RMThe business code is no different from other ordinary projects......
## 创建一个TC
同样引入pom依赖、做好seata配置,与RM无异
```java
@GlobalTransactional
public String deleteUser(){
//微服务1
userService.selectUser();
//微服务2
userService.delUser();
int i = userMapper.deleteById("1");
return i==1?"删除成功":"删除失败";
}
通过@GlobalTransactionalAnnotations perform global transaction management,Failure on one side of the microservice will result in a global rollback
先自我介绍一下,小编13年上师交大毕业,曾经在小公司待过,去过华为OPPO等大厂,18年进入阿里,直到现在.深知大多数初中级java工程师,想要升技能,往往是需要自己摸索成长或是报班学习,但对于培训机构动则近万元的学费,着实压力不小.自己不成体系的自学效率很低又漫长,而且容易碰到天花板技术停止不前.因此我收集了一份《java开发全套学习资料》送给大家,初衷也很简单,就是希望帮助到想自学又不知道该从何学起的朋友,同时减轻大家的负担.添加下方名片,即可获取全套学习资料哦
边栏推荐
- 图神经网络(GNN)的简介「建议收藏」
- 30 lines of code to realize serverless real-time health code recognition -- operation manual
- js true 3d histogram plugin
- uniapp/小程序 onload方法每次打开页面都执行解读
- Set proxy server (Google+IE) "Recommended Collection"
- #Summer Challenge#[FFH] OpenHarmony Device Development Foundation (3) Compilation Dependencies
- Wireless vibrating wire acquisition instrument remote modification method
- photo-sphere-viewer Chinese documentation
- [b01lers2020]Welcome to Earth-1
- 数据湖(三):Hudi概念术语
猜你喜欢
随机推荐
FreeRTOS--栈实验
你知道图论的spfa吗?
RESTful style (detailed introduction + case implementation)
Hand rolled architecture, 41 Redis interview asked
智能手表前景如何?
SQL Server database generation and execution of SQL scripts
Wireless vibrating wire acquisition instrument remote modification method
kvm部署
图论之Floyd,多源图最短路如何暴力美学?
SQL Server2019安装步骤及脱机安装Microsoft机器学习组件下一步不能继续的问题
设置代理服务器(谷歌+IE)「建议收藏」
selenium chrome driver运行时的cannot determine loading status from target frame detached问题
路由-嵌套路由
linux basic command explanation
0801~ Interview questions
图论之Prim,最小生成树该怎么解?
uniapp/小程序 onload方法每次打开页面都执行解读
js semi-circle loading progress animation js special effects
SQL Server 数据库之生成与执行 SQL 脚本
30 lines of code to realize serverless real-time health code recognition -- operation manual








