一、下载seata-server
二、新建seata库,生成表
-- -------------------------------- 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_status_gmt_modified` (`status` , `gmt_modified`),
KEY `idx_transaction_id` (`transaction_id`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4;
-- 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 = utf8mb4;
-- the table to store lock data
CREATE TABLE IF NOT EXISTS `lock_table`
(
`row_key` VARCHAR(128) NOT NULL,
`xid` VARCHAR(128),
`transaction_id` BIGINT,
`branch_id` BIGINT NOT NULL,
`resource_id` VARCHAR(256),
`table_name` VARCHAR(32),
`pk` VARCHAR(36),
`status` TINYINT NOT NULL DEFAULT '0' COMMENT '0:locked ,1:rollbacking',
`gmt_create` DATETIME,
`gmt_modified` DATETIME,
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;
CREATE TABLE IF NOT EXISTS `distributed_lock`
(
`lock_key` CHAR(20) NOT NULL,
`lock_value` VARCHAR(20) NOT NULL,
`expire` BIGINT,
primary key (`lock_key`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4;
INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('AsyncCommitting', ' ', 0);
INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('RetryCommitting', ' ', 0);
INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('RetryRollbacking', ' ', 0);
INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('TxTimeoutCheck', ' ', 0);
在其他业务库里添加这个表
CREATE TABLE `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`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='AT transaction mode undo table';
三、修改seata-server中的application.yml文件
server:
port: 7091
spring:
application:
name: zk-seata-server
profiles:
# 环境配置
active: dev
logging:
config: classpath:logback-spring.xml
file:
path: D:\Program Files\seata\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: file
nacos:
server-addr: 127.0.0.1:8848
namespace: ""
group: DEFAULT_GROUP
username:
password:
##if use MSE Nacos with auth, mutex with username/password attribute
#access-key: ""
#secret-key: ""
data-id: zk-seata-server.yml
registry:
# support: nacos, eureka, redis, zk, consul, etcd3, sofa
type: nacos
nacos:
application: zk-seata-server
server-addr: 127.0.0.1:8848
group : "DEFAULT_GROUP"
cluster : "default"
namespace: "ac15a677-e9ca-4cc2-af41-d0928c225cbb"
username: ""
password: ""
#store:
# support: file 、 db 、 redis
# mode: db
# db:
# datasource: druid
# db-type: mysql
# driver-class-name: com.mysql.jdbc.Driver
# url:
# user:
# 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
四、在nacos上创建seata的配置文件
名称要跟第三步里的data-id一致
store:
# support: file 、 db 、 redis
mode: db
db:
datasource: druid
db-type: mysql
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://172.16.15.21:3306/zk_biz_center_seata?rewriteBatchedStatements=true
user: root
password: admin_1234
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
metrics:
enabled: false
registryType: compact
exporterList: prometheus
exporterPrometheusPort: 9898
transport:
type: TCP
server: NIO
heartbeat: true
enableTmClientBatchSendRequest: false
enableRmClientBatchSendRequest: true
enableTcServerBatchSendResponse: false
rpcRmRequestTimeout: 30000
rpcTmRequestTimeout: 30000
rpcTcRequestTimeout: 30000
threadFactory:
bossThreadPrefix: NettyBoss
workerThreadPrefix: NettyServerNIOWorker
serverExecutorThreadPrefix: NettyServerBizHandler
shareBossWorker: false
clientSelectorThreadPrefix: NettyClientSelector
clientSelectorThreadSize: 1
clientWorkerThreadPrefix: NettyClientWorkerThread
bossThreadSize: 1
workerThreadSize: default
shutdown:
wait: 3
serialization: seata
compressor: none
server:
service-port: 8091 #If not configured, the default is '${server.port} + 1000'
max-commit-retry-timeout: -1
max-rollback-retry-timeout: -1
rollback-retry-timeout-unlock-enable: false
enable-check-auth: true
enable-parallel-request-handle: true
retry-dead-threshold: 130000
xaer-nota-retry-timeout: 60000
recovery:
handle-all-session-period: 1000
undo:
log-save-days: 7
log-delete-period: 86400000
session:
branch-async-queue-size: 5000 #branch async remove queue size
enable-branch-async-remove: false #enable to asynchronous remove branchSession
client:
rm:
asyncCommitBufferLimit: 10000
lock:
retryInterval: 10
retryTimes: 30
retryPolicyBranchRollbackOnConflict: true
reportRetryCount: 5
tableMetaCheckEnable: true
tableMetaCheckerInterval: 60000
sqlParserType: druid
reportSuccessEnable: false
sagaBranchRegisterEnable: false
sagaJsonParser: fastjson
tccActionInterceptorOrder: -2147482648
tm:
commitRetryCount: 5
rollbackRetryCount: 5
defaultGlobalTransactionTimeout: 60000
degradeCheck: false
degradeCheckAllowTimes: 10
degradeCheckPeriod: 2000
interceptorOrder: -2147482648
undo:
dataValidation: true
logSerialization: jackson
onlyCareUpdateColumns: true
logTable: undo_log
compress:
enable: true
type: zip
threshold: 64k
五、修改客户端的配置文件
在需要用到分布式事务的服务的配置文件里增加一下内容
seata:
config:
# support: nacos, consul, apollo, zk, etcd3
type: file
nacos:
server-addr: 127.0.0.1:8848
namespace:
group: DEFAULT_GROUP
username:
password:
##if use MSE Nacos with auth, mutex with username/password attribute
#access-key: ""
#secret-key: ""
data-id: zk-seata-server.yml
registry:
# support: nacos, eureka, redis, zk, consul, etcd3, sofa
type: nacos
nacos:
application: zk-seata-server
server-addr: 127.0.0.1:8848
group : "DEFAULT_GROUP"
cluster : "default"
namespace:
username:
password:
tx-service-group: default_tx_group
service:
vgroup-mapping:
default_tx_group: default #这里需要跟第三步里的cluster保持一致
六,项目中引入依赖
<!-- SpringBoot Seata -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-seata</artifactId>
</dependency>
七,使用注解
@GlobalTransactional(rollbackFor = Exception.class)