Spring Cloud Nacos集成Seata2.0 AT模式
以CentOS 7为例,介绍Spring Cloud Nacos集成Seata2.0 AT模式的流程。分成两个步骤:1.安装配置seata-server、2.项目集成seata-client
一、下载seata-server安装包
根据自己的操作系统选择要下载的安装包格式:下载地址
二、解压安装
将安装包放到指定目录(以/usr/soft/seata为例)
解压,重命名
tar -zxvf seata-server-2.0.0.tar.gz
mv seata seata-server-2.0.0
创建生成环境和开发环境目录:
mkdir dev
mkdir prod
将解压后的seata-server-2.0.0拷贝到dev目录下,进入dev目录下:
cp seata-server-2.0.0 -a dev/
cd dev
三、修改seata配置
修改conf目录下的application.yml:
server:port: 7091spring:application:name: seata-serverlogging:config: classpath:logback-spring.xmlfile:path: ${log.home:${user.home}/logs/seata}extend:logstash-appender:destination: 127.0.0.1:4560kafka-appender:bootstrap-servers: 127.0.0.1:9092topic: logback_to_logstashconsole:user:username: seatapassword: seata# 这里是主要的配置文件
seata:config:# support: nacos, consul, apollo, zk, etcd3type: nacosnacos:server-addr: 127.0.0.1:8848username: nacospassword: nacos# 如果在nacos上添加了命名空间,则配置命名空间IDnamespace: fba13bcb-xxxxx-c9a0e # dev# 配置分组group: SEATA_GROUPcontext-path:##if use MSE Nacos with auth, mutex with username/password attribute#access-key:#secret-key:data-id: seataServer.propertiesregistry:# support: nacos 、 eureka 、 redis 、 zk 、 consul 、 etcd3 、 sofatype: nacospreferred-networks: 30.240.*nacos:application: seata-serverserver-addr: 127.0.0.1:8848username: nacospassword: nacosnamespace: fba13bcb-xxxx-c9a0e # devgroup: DEFAULT_GROUPcluster: defaultcontext-path:##if use MSE Nacos with auth, mutex with username/password attribute#access-key:#secret-key:server:service-port: 8091 #If not configured, the default is '${server.port} + 1000'max-commit-retry-timeout: -1max-rollback-retry-timeout: -1rollback-retry-timeout-unlock-enable: falseenable-check-auth: trueenable-parallel-request-handle: trueenable-parallel-handle-branch: falseretry-dead-threshold: 130000xaer-nota-retry-timeout: 60000enableParallelRequestHandle: truerecovery:committing-retry-period: 1000async-committing-retry-period: 1000rollbacking-retry-period: 1000timeout-retry-period: 1000undo:log-save-days: 7log-delete-period: 86400000session:branch-async-queue-size: 5000 #branch async remove queue sizeenable-branch-async-remove: false #enable to asynchronous remove branchSessionstore:# support: file 、 db 、 redis 、 raftmode: dbsession:mode: dblock:mode: dbdb:datasource: druiddb-type: mysqldriver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://127.0.0.1:3306/mingink-seata?rewriteBatchedStatements=true&&useSSL=falseuser: rootpassword: rootmin-conn: 10max-conn: 100global-table: global_tablebranch-table: branch_tablelock-table: lock_tabledistributed-lock-table: distributed_lockquery-limit: 1000max-wait: 5000metrics:enabled: falseregistry-type: compactexporter-list: prometheusexporter-prometheus-port: 9898transport:rpc-tc-request-timeout: 15000enable-tc-server-batch-send-response: falseshutdown:wait: 3thread-factory:boss-thread-prefix: NettyBossworker-thread-prefix: NettyServerNIOWorkerboss-thread-size: 1security:secretKey: SeataSecretKey0c382ef121d778043159209298fd40bf3850a017tokenValidityInMilliseconds: 1800000ignore:urls: /,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.jpeg,/**/*.ico,/api/v1/auth/login,/metadata/v1/**
为了让tc服务的集群可以共享配置,我们选择了nacos作为统一配置中心。因此服务端配置文件seataServer.properties文件需要在nacos中配好。在nacos的dev环境中创建seataServer的配置文件:
配置内容如下:
# 数据存储方式,db代表数据库
store.mode=db
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/mingink-seata?useUnicode=true&rewriteBatchedStatements=true&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.distributedLockTable=distributed_lock
store.db.maxWait=5000
# 事务、日志等配置
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.undo.logSaveDays=7
server.undo.logDeletePeriod=86400000# 客户端与服务端传输方式
transport.serialization=seata
transport.compressor=none
# 关闭metrics功能,提高性能
metrics.enabled=false
metrics.registryType=compact
metrics.exporterList=prometheus
metrics.exporterPrometheusPort=9898
四、创建数据库表
特别注意:tc服务在管理分布式事务时,需要记录事务相关数据到数据库中,这些表主要记录全局事务、分支事务、全局锁信息,你需要提前创建好这些表。
新建一个名为mingink-seata的数据库(数据库名可以自定义,注意与上面配置对应上):
-- -------------------------------- The script used when storeMode is 'db' --------------------------------
-- the table to store GlobalSession data(可以在/script/server/db/mysql.sql找到对应版本的sql文件)
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 = InnoDBDEFAULT 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 = InnoDBDEFAULT 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` (`xid`)
) ENGINE = InnoDBDEFAULT 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 = InnoDBDEFAULT 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);
在你的项目数据库上创建一个undo_log表:
-- 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 NOT NULL COMMENT 'branch transaction id',`xid` VARCHAR(128) 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 = InnoDBAUTO_INCREMENT = 1DEFAULT CHARSET = utf8 COMMENT ='AT transaction mode undo table';
五、启动加粗样式seata-server(TC)服务
在bin目录下找到startup.sh文件,编辑启动命令行:
vim startup.sh
内容如下:
./seata-server.sh -h 127.0.0.1 -p 8091
注意:如果seata-server与你的项目服务在同一台主机可以使用127.0.0.1,如果不再同一台主机(比如seata-server部署在ip为11.22.33.44的服务器,项目服务启动在你的本地主机),那么这里的ip应修改为服务器的ip11.22.33.44,否则会出现本地服务找不到seata-server服务的异常
然后再bin目录下启动seata-server使其注册到nacos上:
sh startup.sh
打开nacos控制面板,找到命名空间对应的服务列表:
可以发现,我们的seata-server已经成功注册到nacos上了。在localhost:7091可以访问seata控制台
附:
- 重启seata-server前需要终止之前启动的进程,netstat -anp | grep 8091查看进程号,kill -9 pid 终止进程;
- 如果seata-server没有注册到nacos上,或者seata控制台 无法打开,可能是因为你的服务器没有开放8091和7091端口;
六、Spring Cloud整合Seata
添加Seata依赖
<!-- SpringCloud Alibaba Nacos Config --><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId></dependency><!-- seata模块 --><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><dependency><groupId>io.seata</groupId><artifactId>seata-spring-boot-starter</artifactId><version>2.0.0</version></dependency>
添加yml配置
# Seata
seata:registry: # TC服务注册中心的配置,微服务根据这些信息去注册中心获取tc服务地址# 参考tc服务自己的registry.conf中的配置type: nacosnacos: # tcserver-addr: 127.0.0.1:8848username: nacospassword: nacosnamespace: ${spring.cloud.nacos.discovery.namespace}group: DEFAULT_GROUPcluster: defaultapplication: seata-server # tc服务在nacos中的服务名称tx-service-group: seata-group # 事务组,根据这个获取tc服务的cluster名称service:vgroup-mapping: # 事务组与TC服务cluster的映射关系seata-group : default# 开启数据源的代理模式data-source-proxy-mode: AT # 默认就是AT
注解
在AT模式中,使用@GlobalTransactional注解即可设置全局事务:
例如,我的MingInk-User服务中,有个register业务,它依赖于MingInk-Gorse服务的另一个业务,中间通过Open Feign进行远程调用:
@Override@GlobalTransactionalpublic R<?> registerUser(User user) {log.info("Begin Register: 【{}】", user.getUserName());// 检测用户信息格式是否正确....// 插入新用户user.setUserId(SnowFlakeFactory.getSnowFlakeFromCache().nextId()); // 雪花算法设置用户Iduser.setUid((String.valueOf(userMapper.selectList(null).size() + 100001))); // 设置用户Uiduser.setNickName(user.getUserName()); // 默认新用户昵称为用户(账户)名user.setAvatar("null"); // 设置用户默认头像user.setBirthday(new Date());user.setStatus(0); // 默认用户状态为正常——0user.setLoginDate(new Date()); // 最近登录时间user.setCreateTime(new Date()); // 当前时间user.setUpdateTime(new Date()); // 当前时间boolean isInsertSuccess = userMapper.insert(user) > 0; // 返回值int代表插入成功条数,大于0表示插入成功条数,等于0则代表插入失败if (!isInsertSuccess) {log.info("用户[{}]注册失败:", user.getUserName());return R.fail("用户注册失败");}// 设置默认权限roleService.addUserRole(user.getUserId(), 3L);// 注册Gorse UserGorseUserRequest gorseUserRequest = new GorseUserRequest();gorseUserRequest.setUserId(user.getUserId());gorseUserRequest.setLabels("[]");if (!remoteGorseService.addNewGorseUser(gorseUserRequest)) { // 这是MingInk-Gorse服务的方法// 注册Gorse User失败log.info("用户[{}]注册Gorse User失败:", user.getUserName());return R.fail("用户注册失败");}log.info("用户[{}]注册成功:", user.getUserName());return R.ok(null, "用户注册成功");}
在MingInk-Gorse服务的addNewGorseUser方法中,我们也需要给它加上@GlobalTransactional全局事务注解,让它也能注册到事务管理器中,使得全局事务生效:
@GlobalTransactionalpublic boolean addNewGorseUser(GorseUserRequest gorseUserRequest) {GorseUser gorseUser = new GorseUser();gorseUser.setUserId(gorseUserRequest.getUserId());gorseUser.setLabels(gorseUserRequest.getLabels());gorseUser.setComment("");gorseUser.setSubscribe("[]");return gorseUsersMapper.insert(gorseUser) > 0;}
通过上述配置,如果普通用户注册成功,但是Gorse用户没有注册成功,会将之前执行的SQL进行回滚。
七、多seata-server部署
将dev目录下的seata-server-2.0.0拷贝到prod目录下:
# 进入dev目录
cd /usr/soft/seata/dev/
# 拷贝文件
cp -a seata-server-2.0.0/ ../prod
修改prod目录下seata配置中的服务启动端口号以及控制台运行端口号:
cd /usr/soft/seata/prod/seata-server-2.0.0/conf
vim application.yml
application.yml
由于我们希望新的seata-server服务运行在nacos的prod命名空间下,因此需要修改响应的namespace:
端口号发生了改变,需要同时修改bin目录下的startup.sh:
./seata-server.sh -h 127.0.0.1 -p 8092
在nacos的prod命名空间下可以看到新启动的seata-server服务,这样就能跟dev开发环境区分开来了: