当前位置:网站首页>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开发全套学习资料》送给大家,初衷也很简单,就是希望帮助到想自学又不知道该从何学起的朋友,同时减轻大家的负担.添加下方名片,即可获取全套学习资料哦
边栏推荐
- 麻烦问一下,对mysql 场景注入故障,是不是不是对mysql server 端注入故障,只是对ja
- Openlayers Quick Start Tutorial
- php——三篇夯实根基第一篇
- 智能手表前景如何?
- PHP+MYSQL [Student Information Management System] (Minimalist Edition)
- 新特性解读 | MySQL 8.0 GIPK 不可见主键
- To eliminate air bubbles to save the mushroom h5 small game source code
- 自动生成代码器推荐-code-gen
- pytorch模型转tensorflow模型
- uniapp/小程序 onload方法每次打开页面都执行解读
猜你喜欢
随机推荐
ThinkPHP 5.1反序列化分析和poc
Custom mvc framework review
智能图像分析-智能家用电器图像目标检测统计计数检测与识别-艾科瑞特科技(iCREDIT)
Basic operations of openGauss database (super detailed)
单例模式的七种写法,你都知道吗?
Process finished with exit code 1
package.json与package-lock.json
js半圆环加载进度动画js特效
Intelligent Image Analysis-Intelligent Home Appliance Image Target Detection Statistical Counting Detection and Recognition-iCREDIT
工厂方法模式
Taurus.MVC V3.0.3 Microservice Open Source Framework Released: Make the evolution of .NET architecture easier in large concurrency.
js秒表倒计时插件
RestTemplate use: set request header, request body
pgsql数据库实现导入导出
吾爱第三课-修改版权和资源
OpenFeign设置header的3种方式
How to better assess credit risk?Just watch this scorecard model live
Intouch System Platform IDE-1
photo-sphere-viewer中文文档
Hand rolled architecture, 41 Redis interview asked