抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

Seata 使用

Seata-Server安装配置

seata-server为seata中的事务协调器。

注意:只能在jdk8及以上环境运行

下载Seata-Server

下载地址:https://github.com/seata/seata/releases

image-20210301162221916

nacos配置

nacos 安装

nacos 安装参考 https://baiyp.ren/Nacos%E9%83%A8%E7%BD%B2.html

nacos配置
添加命名空间

在命名空间配置项添加 seata的配置

image-20210301163808700

配置Seata-Server

配置file.conf

​ 解压seata-server安装包到指定目录,修改conf目录下的file.conf配置文件,主要修改事务日志存储模式为db及数据库连接信息;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
## 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"
#不要用mysql8的驱动,否则报错
driverClassName = "com.mysql.jdbc.Driver"
#修改数据库连接地址
url = "jdbc:mysql://127.0.0.1:3306/seata"
#修改数据库用户名
user = "root"
#修改数据库密码
password = "root"
minConn = 5
maxConn = 100
globalTable = "global_table"
branchTable = "branch_table"
lockTable = "lock_table"
queryLimit = 100
maxWait = 5000
}

## redis store property
redis {
host = "127.0.0.1"
port = "6379"
password = ""
database = "0"
minConn = 1
maxConn = 10
maxTotal = 100
queryLimit = 100
}

}
配置registry.conf

修改conf目录下的registry.conf配置文件,主要修改seata-server注册中心配置以及配置中心配置,这里选择nacos作为注册中心以及配置中心,注意z配置nacos的命名空间为seata命名空间的id

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
registry {
# file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
# 设置使用nacos注册中心
type = "nacos"
loadBalance = "RandomLoadBalance"
loadBalanceVirtualNodes = 10
# nacos的注册中心配置
nacos {
# 配置seata服务名称
application = "seata-server"
# nacos的连接地址
serverAddr = "52.82.98.209:9105"
# 分组名称
group = "SEATA_GROUP"
# 注意z配置nacos的命名空间为seata命名空间的id
namespace = "dfcf36cb-00fa-4dd5-a488-6ccb7b97e0a3"
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
#使用nacos配置中心
type = "nacos"
# nacos的配置中心配置
nacos {
# nacos的连接地址
serverAddr = "52.82.98.209:9105"
# 注意z配置nacos的命名空间为seata命名空间的id
namespace = "dfcf36cb-00fa-4dd5-a488-6ccb7b97e0a3"
# 分组名称
group = "SEATA_GROUP"
username = ""
password = ""
}
consul {
serverAddr = "127.0.0.1:8500"
}
apollo {
appId = "seata-server"
apolloMeta = "http://192.168.1.204:8801"
namespace = "application"
apolloAccesskeySecret = ""
}
zk {
serverAddr = "127.0.0.1:2181"
sessionTimeout = 6000
connectTimeout = 2000
username = ""
password = ""
}
etcd3 {
serverAddr = "http://localhost:2379"
}
file {
name = "file.conf"
}
}

配置Seata-Server环境

查看文档

打开conf目录下的README-zh.md文档

image-20210301164802444

导入Seata-Server数据库

打开server脚本 下的db文件夹,根据不同的数据库选择不同的数据库脚本

image-20210301165032282

以下是具体mysql脚本内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
-- -------------------------------- 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_gmt_modified_status` (`gmt_modified`, `status`),
KEY `idx_transaction_id` (`transaction_id`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8;

-- 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 = utf8;

-- the table to store lock data
CREATE TABLE IF NOT EXISTS `lock_table`
(
`row_key` VARCHAR(128) NOT NULL,
`xid` VARCHAR(96),
`transaction_id` BIGINT,
`branch_id` BIGINT NOT NULL,
`resource_id` VARCHAR(256),
`table_name` VARCHAR(32),
`pk` VARCHAR(36),
`gmt_create` DATETIME,
`gmt_modified` DATETIME,
PRIMARY KEY (`row_key`),
KEY `idx_branch_id` (`branch_id`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8;

因为本地环境是使用mysql,下载mysql.sql,创建seata的数据库,将mysql.sql导入到seata数据库

image-20210301165213559

导入nacos配置
下载文件

打开config-center 脚本 ,下载config.txt 以及nacos目录

image-20210301165529589

修改config.txt

注意 加注释的是需要注意的地址,如果有不同的地址需要修改

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
transport.type=TCP
transport.server=NIO
transport.heartbeat=true
transport.enableClientBatchSendRequest=false
transport.threadFactory.bossThreadPrefix=NettyBoss
transport.threadFactory.workerThreadPrefix=NettyServerNIOWorker
transport.threadFactory.serverExecutorThreadPrefix=NettyServerBizHandler
transport.threadFactory.shareBossWorker=false
transport.threadFactory.clientSelectorThreadPrefix=NettyClientSelector
transport.threadFactory.clientSelectorThreadSize=1
transport.threadFactory.clientWorkerThreadPrefix=NettyClientWorkerThread
transport.threadFactory.bossThreadSize=1
transport.threadFactory.workerThreadSize=default
transport.shutdown.wait=3
# 注意修改事务分组名称要保证客户端服务器端以及nacos配置是一致的
service.vgroupMapping.my_test_tx_group=default
# 注意修改seata-server的地址,如果seata-server 地址不在本地需要修改
service.default.grouplist=127.0.0.1:8091
service.enableDegrade=false
service.disableGlobalTransaction=false
client.rm.asyncCommitBufferLimit=10000
client.rm.lock.retryInterval=10
client.rm.lock.retryTimes=30
client.rm.lock.retryPolicyBranchRollbackOnConflict=true
client.rm.reportRetryCount=5
client.rm.tableMetaCheckEnable=false
client.rm.tableMetaCheckerInterval=60000
client.rm.sqlParserType=druid
client.rm.reportSuccessEnable=false
client.rm.sagaBranchRegisterEnable=false
client.tm.commitRetryCount=5
client.tm.rollbackRetryCount=5
client.tm.defaultGlobalTransactionTimeout=60000
client.tm.degradeCheck=false
client.tm.degradeCheckAllowTimes=10
client.tm.degradeCheckPeriod=2000
# 注意修改事务的存储方式,和服务端配置一致选择db模式
store.mode=db
store.publicKey=
store.file.dir=file_store/data
store.file.maxBranchSessionSize=16384
store.file.maxGlobalSessionSize=512
store.file.fileWriteBufferCacheSize=16384
store.file.flushDiskMode=async
store.file.sessionReloadReadSize=100
# 注意配置数据库的连接配置
store.db.datasource=druid
store.db.dbType=mysql
store.db.driverClassName=com.mysql.jdbc.Driver
# mysql连接地址配置
store.db.url=jdbc:mysql://127.0.0.1:3306/seata?useUnicode=true&rewriteBatchedStatements=true
# mysql用户名密码配置
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
store.redis.mode=single
store.redis.single.host=127.0.0.1
store.redis.single.port=6379
store.redis.maxConn=10
store.redis.minConn=1
store.redis.maxTotal=100
store.redis.database=0
store.redis.password=
store.redis.queryLimit=100
server.recovery.committingRetryPeriod=1000
server.recovery.asynCommittingRetryPeriod=1000
server.recovery.rollbackingRetryPeriod=1000
server.recovery.timeoutRetryPeriod=1000
server.maxCommitRetryTimeout=-1
server.maxRollbackRetryTimeout=-1
server.rollbackRetryTimeoutUnlockEnable=false
client.undo.dataValidation=true
client.undo.logSerialization=jackson
client.undo.onlyCareUpdateColumns=true
server.undo.logSaveDays=7
server.undo.logDeletePeriod=86400000
client.undo.logTable=undo_log
client.undo.compress.enable=true
client.undo.compress.type=zip
client.undo.compress.threshold=64k
log.exceptionRate=100
transport.serialization=seata
transport.compressor=none
metrics.enabled=false
metrics.registryType=compact
metrics.exporterList=prometheus
metrics.exporterPrometheusPort=9898
导入配置

将下载的文件保存成如下的结构,执行nacos目录中的nacos-config.sh

image-20210301170816182

进入nacos目录使用给git bash执行导入命令

image-20210301170850014

执行如下命令进行导入操作

-h 指定nacos的地址

-p 指定nacos的端口号

-t 指定刚刚在nacos创建的seata的命名空间ID

1
sh nacos-config.sh -h 52.82.98.209 -p 9105 -t dfcf36cb-00fa-4dd5-a488-6ccb7b97e0a3

image-20210301171226060

如果出现以上命令表示导入成功,可以打开nacos进行查看

image-20210301171355912

启动Seata-server

到Seata-server的bin目录执行seata-server.bat命令脚本

image-20210301171622985

执行后,如果出现如下界面表示启动成功

image-20210301171726572

AT模式配置

seata默认就是at模式直接配置就可以

环境配置

导入undo_log表

打开client 脚本 ,下载at/db目录下的mysql.sql脚本,可以根据具体数据库选择不同的脚本文件

image-20210301180842650

以下是具体mysql脚本内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
-- for AT mode you must to init this sql for you business database. the seata server not need it.
CREATE TABLE IF NOT EXISTS `undo_log`
(
`branch_id` BIGINT(20) NOT NULL COMMENT 'branch transaction id',
`xid` VARCHAR(100) NOT NULL COMMENT 'global transaction id',
`context` VARCHAR(128) NOT NULL COMMENT 'undo_log context,such as serialization',
`rollback_info` LONGBLOB NOT NULL COMMENT 'rollback info',
`log_status` INT(11) NOT NULL COMMENT '0:normal status,1:defense status',
`log_created` DATETIME(6) NOT NULL COMMENT 'create datetime',
`log_modified` DATETIME(6) NOT NULL COMMENT 'modify datetime',
UNIQUE KEY `ux_undo_log` (`xid`, `branch_id`)
) ENGINE = InnoDB
AUTO_INCREMENT = 1
DEFAULT CHARSET = utf8 COMMENT ='AT transaction mode undo table';
导入pom文件

因为我们的seata-server是使用的1.4.0 所以客户端也需要导入1.4.0,在需要用到seata的客户端(TM,RM)都需要导入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!--seata 的启动器 需要导入对应的版本 -->
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-spring-boot-starter</artifactId>
<version>1.4.0</version>
</dependency>
<!--seata 对应的cloud版本 对于 各种中间件的支持,用于xid的传递,比如fegin Hystrix Sentinel等 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-seata</artifactId>
<version>${spring-boot.version}</version>
<!-- 需要排除自带的 seata-spring-boot-starter 因为默认是 1.3.0 版本-->
<exclusions>
<exclusion>
<groupId>io.seata</groupId>
<artifactId>seata-spring-boot-starter</artifactId>
</exclusion>
</exclusions>
</dependency>

TM 配置

TM是事务管理器,就是开启分布式事务的客户端需要做如下操作,TM可以不包含数据源

  • 在TM启动类添加 @EnableTransactionManagement
  • 在事务的开启方法加上 @GlobalTransactional 注解
目录结构

image-20210301190839190

配置application配置文件

需要配置application.yml配置文件

1
2
3
4
5
6
7
8
9
10
seata:
enabled: true
application-id: ${spring.application.name}
tx-service-group: my_test_tx_group
config:
type: nacos
nacos:
namespace: "dfcf36cb-00fa-4dd5-a488-6ccb7b97e0a3"
server-addr: @nacos.addr@
group: SEATA_GROUP
启动类配置

注意只要在启动类配置上@EnableTransactionManagement即可

1
2
3
4
5
6
7
8
9
10
11
@SpringBootApplication
//启用Nacos注册中心
@EnableDiscoveryClient
//开启fegin支持,clients是指哪个类开启fegin
@EnableFeignClients(basePackages = {"com.heima.fullink.service"})
@EnableTransactionManagement
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class);
}
}
开启事务

需要在开启事务的方法上面加上@GlobalTransactional注解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@RequestMapping("/placeOrder")
@GlobalTransactional(name = "my-test-create-order", rollbackFor = Exception.class)
public ResponseVO testSeata(@RequestBody OrderVO orderVO) {
orderVO.setId(String.valueOf(idWorker.nextId()));
orderVO.setStatus(1);
storageOrderService.insert(orderVO);
//出错回滚测试
int n = 1/0;
ProductPO productPO = storageProductService.findByID(orderVO.getProductId());
if (null != productPO) {
productPO.setStock(productPO.getStock() - 1);
productPO.setStatus(true);
// productPO.setProductCode("iphone11");
}
storageProductService.updateById(productPO);
return ResponseVO.success(null, "修改成功");
}

RM 配置

RM是负责提交和回滚事务的,开启RM只需要如下配置

  • 配置application配置文件
  • 在需要提交事务的方法上面加入@Transactional注解
目录结构

image-20210301190742445

配置application配置文件

需要配置application.yml配置文件

1
2
3
4
5
6
7
8
9
10
seata:
enabled: true
application-id: ${spring.application.name}
tx-service-group: my_test_tx_group
config:
type: nacos
nacos:
namespace: "dfcf36cb-00fa-4dd5-a488-6ccb7b97e0a3"
server-addr: @nacos.addr@
group: SEATA_GROUP
开启事务

在需要提交事务的方法上加入@Transactional注解

1
2
3
4
5
@RequestMapping("/updateById")
@Transactional
public void updateById(@RequestBody ProductPO productPO) {
productMapper.updateById(productPO);
}

评论