安装包下载地址:Release v1.5.1 · seata/seata · GitHub
seata-server-1.5.1.zip 包含seata服务启动脚本、application.yml配置文件
Source code 源码包
1、搭建seata-server1.1、修改seataconf中的application.yml配置文件
server:
port: 8091
spring:
application:
name: seata-server
logging:
config: classpath:logback-spring.xml
file:
path: ${user.home}/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: nacos
nacos:
server-addr: 127.0.0.1:8848
namespace: 5b1e072e-e720-46b8-8eae-2313ce52365f
group: DEFAULT_GROUP
username: nacos
password: nacos
##if use MSE Nacos with auth, mutex with username/password attribute
#access-key: ""
#secret-key: ""
data-id: seataServer.properties
registry:
# support: nacos, eureka, redis, zk, consul, etcd3, sofa
type: nacos
nacos:
application: seata-server
server-addr: 127.0.0.1:8848
group: DEFAULT_GROUP
namespace: 5b1e072e-e720-46b8-8eae-2313ce52365f
cluster: default
username: nacos
password: nacos
# 以下存储配置,可以配置在nacos的seataServer.properties
# store:
# support: file 、 db 、 redis
# mode: db
# db:
# datasource: druid
# db-type: mysql
# driver-class-name: com.mysql.jdbc.Driver
# url: jdbc:mysql://127.0.0.1:3306/seata?rewriteBatchedStatements=true
# user: root
# password: 123456
# 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
2、导入配置文件到nacos
2.1、通过data-id创建配置文件
2.1.1 在nacos中新建seataServer.properties配置与application.yml和bootstrap.yml一致
添加配置内容
service.vgroupMapping.my_test_tx_group=default store.mode=db store.redis.host=127.0.0.1 store.redis.port=6379 store.redis.maxConn=10 store.redis.minConn=1 store.redis.database=0 store.redis.queryLimit=100 #store.lock.mode=db #store.session.mode=db #store.publicKey= store.db.datasource=druid store.db.dbType=mysql store.db.driverClassName=com.mysql.jdbc.Driver store.db.url=jdbc:mysql://127.0.0.1:3306/seata?useUnicode=true&rewriteBatchedStatements=true store.db.user=root store.db.password=123456 store.db.minConn=5 store.db.maxConn=30 store.db.globalTable=global_table store.db.branchTable=branch_table store.db.distributedLockTable=distributed_lock store.db.queryLimit=100 store.db.lockTable=lock_table store.db.maxWait=5000 #Transaction rule configuration, only for the server 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 server.distributedLockExpireTime=10000 server.xaerNotaRetryTimeout=60000 server.session.branchAsyncQueueSize=5000 server.session.enableBranchAsyncRemove=false #Transaction rule configuration, only for the client 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=true client.rm.tableMetaCheckerInterval=60000 client.rm.sqlParserType=druid client.rm.reportSuccessEnable=false client.rm.sagaBranchRegisterEnable=false client.rm.sagaJsonParser=fastjson client.rm.tccActionInterceptorOrder=-2147482648 client.tm.commitRetryCount=5 client.tm.rollbackRetryCount=5 client.tm.defaultGlobalTransactionTimeout=60000 client.tm.degradeCheck=false client.tm.degradeCheckAllowTimes=10 client.tm.degradeCheckPeriod=2000 client.tm.interceptorOrder=-2147482648 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 #For TCC transaction mode tcc.fence.logTableName=tcc_fence_log tcc.fence.cleanPeriod=1h #Log rule configuration, for client and server log.exceptionRate=100 #Metrics configuration, only for the server metrics.enabled=false metrics.registryType=compact metrics.exporterList=prometheus metrics.exporterPrometheusPort=9898 transport.type=TCP transport.server=NIO transport.heartbeat=true transport.enableTmClientBatchSendRequest=false transport.enableRmClientBatchSendRequest=true transport.enableTcServerBatchSendResponse=false transport.rpcRmRequestTimeout=30000 transport.rpcTmRequestTimeout=30000 transport.rpcTcRequestTimeout=30000 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 transport.serialization=seata transport.compressor=none
注:Seata 启动报错 can not get cluster name in registry config 'service.vgroupMapping.XXX', please make sure registry config correct
需要在nacos中再添加service.vgroupMapping.XXXX配置值为default
3、初始化数据库-- -------------------------------- 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);
4、启动seata服务
在seatabin中执行seata-server.bat文件
http://localhost:8091/#/login 账号密码在application.yml文件中
5、数据库配置在客户端连接的业务数据库 增加 undo_log 表
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 = utf8mb4 COMMENT ='AT transaction mode undo table';
6、在POM中引入依赖
io.seata seata-spring-boot-starter1.5.1 com.alibaba.cloud spring-cloud-starter-alibaba-seataio.seata seata-spring-boot-starter
spring-cloud-starter-alibaba-seata默认引入的是1.3.0版本因此需要手动引入1.5.1版本。
7、在bootstrap.yml中配置seataseata:
enabled: true
application-id: test001-service
tx-service-group: my_test_tx_group
# 是否自动开启数据源代理
enable-auto-data-source-proxy: true
# 数据源代理模式,使用AT模式
data-source-proxy-mode: AT
client:
rm:
lock:
# 校验或占用全局锁重试间隔,单位ms
retry-interval: 10
# 校验或占用全局锁重试次数
retry-times: 30
# 分支事务与其它全局回滚事务冲突时锁策略,true,优先释放本地锁让回滚成功
retry-policy-branch-rollback-on-conflict: true
tm:
# 一阶段全局提交结果上报TC重试次数
commit-retry-count: 5
# 一阶段全局回滚结果上报TC重试次数
rollback-retry-count: 5
# 分布式事物超时时间
default-global-transaction-timeout: 600000
# 降级开关,false 不打开
degrade-check: false
degrade-check-period: 2000
degrade-check-allow-times: 10
undo:
log-serialization: jackson
service:
# 全局事务开关
disable-global-transaction: false
# 配置中心,需要和 seata server 保持一致
config:
type: nacos
nacos:
namespace: 5b1e072e-e720-46b8-8eae-2313ce52365f
server-addr: localhost:8848
group: DEFAULT_GROUP
data-id: seataServer.properties
# 注册中心,需要和 seata server 保持一致
registry:
type: nacos
nacos:
application: seata-server
group: DEFAULT_GROUP
namespace: 5b1e072e-e720-46b8-8eae-2313ce52365f
server-addr: localhost:8848
log:
exception-rate: 100
8、测试服务
在需要控制事务的方法上加上注解,如
@GlobalTransactional(name = "my_test_tx_group",rollbackFor = Exception.class)
public void createAccountOrder(Integer accountId, Long amount, boolean hasException){
System.out.println("1、xid:" + RootContext.getXID());
// 1、远程扣减账户余额
String result = accountClient.debit(accountId, amount);
log.info("远程扣减库存结果:[{}]", result);
// 2、下订单
orderService.createOrder(accountId, amount);
if (hasException) {
throw new RuntimeException("发生了异常,分布式事物需要回滚");
}
}
执行效果:
正常:
异常:
服务A
服务B



