SpringCloud(nacos)集成Seata分布式事务
文章目录
技术选型及版本
注册中心:nacos 2.1.0
服务间调用:feign
持久层:mybatis-plus
数据库:mysql 8.0
Springboot:2.6.4
Springcloud:2021.0.1
Springcloud Alibaba:2021.1
jdk:1.8
seata:1.5.2
一、官网地址
http://seata.io/
二、seata server端配置
1、下载解压
2、创建数据库
创建数据库seata_1.5.2(数据库名可随便命名),sql文件在seata-1.5.2\script\server\db文件夹下面,创建表结构:
-- -------------------------------- 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);
3、修改配置文件
3.1 修改seata-1.5.2\conf\下面的application.yml文件,使用nacos做注册中心和配置中心
server:
port: 7091
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: e1e2abf6-d1ad-4fd2-80b5-efc5c9858708
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: e1e2abf6-d1ad-4fd2-80b5-efc5c9858708
cluster: default
username: nacos
password: nacos
# 以下存储配置,可以配置在nacos的seataServer.properties
# store:
# # support: file 、 db 、 redis
# mode: file
# 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
3.2 导入配置文件到nacos
可以专门给seata建立一个命名空间,比如seata
创建文件名seataServer.properties的文件,导入以下内容:
service.vgroupMapping.seata_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.cj.jdbc.Driver
store.db.url=jdbc:mysql://127.0.0.1:3306/seata_1.5.2?useUnicode=true&allowPublicKeyRetrieval=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2b8
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.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
在nacos中再添加service.vgroupMapping.XXXX,其中xxxx为事务组名称,文件的配置值为default
4、启动seata服务
先启动nacos服务,再启动seata服务。
三、Seata客户端配置
1、数据库设置
在每一个需要使用seata客户端的数据库里面加一张表:
DROP TABLE IF EXISTS `undo_log`;
CREATE TABLE `undo_log` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`branch_id` bigint(20) NOT NULL,
`xid` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`context` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`rollback_info` longblob NOT NULL,
`log_status` int(11) NOT NULL,
`log_created` datetime(0) NULL,
`log_modified` datetime(0) NULL,
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `ux_undo_log`(`xid`, `branch_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
2、项目文件配置
2.1 导入maven依赖
<!--seata-->
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-spring-boot-starter</artifactId>
<version>1.5.2</version>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-seata</artifactId>
<exclusions>
<exclusion>
<groupId>io.seata</groupId>
<artifactId>seata-spring-boot-starter</artifactId>
</exclusion>
</exclusions>
</dependency>
2.2 在bootstrap.yml中配置seata
#分布式事务配置
seata:
enabled: true
application-id: ${spring.application.name}
# 注意这个地方必须要是service.vgroupMapping.XXXX的XXXX
tx-service-group: seata_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: e1e2abf6-d1ad-4fd2-80b5-efc5c9858708
server-addr: localhost:8848
group: DEFAULT_GROUP
data-id: seataServer.properties
# 注册中心,需要和 seata server 保持一致
registry:
type: nacos
nacos:
application: seata-server
group: DEFAULT_GROUP
namespace: e1e2abf6-d1ad-4fd2-80b5-efc5c9858708
server-addr: localhost:8848
log:
exception-rate: 100
3、代码中使用
@GlobalTransactional(rollbackFor = Exception.class)
@Override
public Result<Integer> updateUserPhoneAndBookInfo(Integer userId, String phone) throws TransactionException {
//远程方法
Result<Integer> userResult = userClient.updateUserPhone(23, "18200000000");
if(userResult.getData()==0) {
GlobalTransactionContext.reload(RootContext.getXID()).rollback();
return null;
}
Book book = new Book();
book.setId(132);
book.setBookName("测试图书12345");
// 远程方法
Result<Integer> bookResult = bookClient.updateBookInfo(book);
if(bookResult.getData()==0) {
GlobalTransactionContext.reload(RootContext.getXID()).rollback();
return null;
}
int i = 1/0;
return null;
}
4、测试结果
无论是在本地出现异常,还是远程服务出现异常,还是调用远程服务失败,事务都将进行回滚。
5、注意事项
如果远程服务发生异常后,却被feign降级了,导致调用方捕捉不到异常,此时不会进行事务回滚,事务会正常提交,解决此问题的方法是通过判断降级的返回值,手动进行事务的回滚。