seata的部署和集成

一、部署Seata的tc-server

1.下载

首先我们要下载seata-server包,地址在http://seata.io/zh-cn/blog/download.html

2.解压

在非中文目录解压缩这个zip包,其目录结构如下:

3.修改配置

修改conf目录下的registry.conf文件:

内容如下:

 # Seata Registry 配置
 registry {
 ​
   # 注册中心类型,可选值为 "nacos"、"eureka"、"zookeeper" 等
   type = "nacos"
 ​
   nacos {
     # Seata TC 服务注册到 Nacos 的服务名称,可以根据需要自定义
     application = "seata-tc-server"
     # Nacos 服务器地址
     serverAddr = "127.0.0.1:8848"
     # Nacos 分组,默认为 "DEFAULT_GROUP"
     group = "DEFAULT_GROUP"
     # Nacos 命名空间,默认为空
     namespace = ""
     # Nacos 集群名称,默认为 "SH"
     cluster = "SH"
     # Nacos 认证用户名
     username = "nacos"
     # Nacos 认证密码
     password = "nacos"
   }
 }
 ​
 # Seata Config 配置
 config {
 ​
   # 读取 TC 服务端的配置文件的方式,这里是从 Nacos 配置中心读取,以实现 TC 集群共享配置
   type = "nacos"
 ​
   nacos {
     # Nacos 服务器地址
     serverAddr = "127.0.0.1:8848"
     # Nacos 命名空间,默认为空
     namespace = ""
     # Nacos 分组,默认为 "SEATA_GROUP"
     group = "SEATA_GROUP"
     # Nacos 认证用户名
     username = "nacos"
     # Nacos 认证密码
     password = "nacos"
     # Nacos 配置文件的 Data ID
     dataId = "seataServer.properties"
   }
 }
 ​

4.在nacos添加配置

特别注意,为了让tc服务的集群可以共享配置,我们选择了nacos作为统一配置中心。因此服务端配置文件seataServer.properties文件需要在nacos中配好。

格式如下:

配置内容如下:

# Seata 数据存储方式配置
store.mode=db

# 数据库存储配置
store.db.datasource=druid  # 使用 Druid 数据源
store.db.dbType=mysql  # 数据库类型为 MySQL
store.db.driverClassName=com.mysql.jdbc.Driver  # MySQL 驱动
store.db.url=jdbc:mysql://127.0.0.1:3306/seata?useUnicode=true&rewriteBatchedStatements=true  # 数据库连接 URL
store.db.user=root  # 数据库用户名
store.db.password=123  # 数据库密码
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  # 获取连接的最大等待时间

# 事务、日志等配置
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  # Undo 日志保存天数
server.undo.logDeletePeriod=86400000  # Undo 日志删除周期

# 客户端与服务端传输方式
transport.serialization=seata  # 传输方式使用 Seata 序列化
transport.compressor=none  # 不使用压缩

# Metrics 配置
metrics.enabled=false  # 关闭 Metrics 功能
metrics.registryType=compact  # Metrics 注册类型为 Compact
metrics.exporterList=prometheus  # 启用 Prometheus 导出器
metrics.exporterPrometheusPort=9898  # Prometheus 导出器端口

其中的数据库地址、用户名、密码都需要修改成你自己的数据库信息。

5.创建数据库表

特别注意:tc服务在管理分布式事务时,需要记录事务相关数据到数据库中,你需要提前创建好这些表。

新建一个名为seata的数据库,运行课前资料提供的sql文件:

这些表主要记录全局事务、分支事务、全局锁信息:

 ​
 SET NAMES utf8mb4;
 SET FOREIGN_KEY_CHECKS = 0;
 ​
 -- ----------------------------
 -- 分支事务表
 -- ----------------------------
 DROP TABLE IF EXISTS `branch_table`;
 CREATE TABLE `branch_table`  (
   `branch_id` bigint(20) NOT NULL,
   `xid` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
   `transaction_id` bigint(20) NULL DEFAULT NULL,
   `resource_group_id` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
   `resource_id` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
   `branch_type` varchar(8) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
   `status` tinyint(4) NULL DEFAULT NULL,
   `client_id` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
   `application_data` varchar(2000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
   `gmt_create` datetime(6) NULL DEFAULT NULL,
   `gmt_modified` datetime(6) NULL DEFAULT NULL,
   PRIMARY KEY (`branch_id`) USING BTREE,
   INDEX `idx_xid`(`xid`) USING BTREE
 ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
 ​
 -- ----------------------------
 -- 全局事务表
 -- ----------------------------
 DROP TABLE IF EXISTS `global_table`;
 CREATE TABLE `global_table`  (
   `xid` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
   `transaction_id` bigint(20) NULL DEFAULT NULL,
   `status` tinyint(4) NOT NULL,
   `application_id` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
   `transaction_service_group` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
   `transaction_name` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
   `timeout` int(11) NULL DEFAULT NULL,
   `begin_time` bigint(20) NULL DEFAULT NULL,
   `application_data` varchar(2000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
   `gmt_create` datetime NULL DEFAULT NULL,
   `gmt_modified` datetime NULL DEFAULT NULL,
   PRIMARY KEY (`xid`) USING BTREE,
   INDEX `idx_gmt_modified_status`(`gmt_modified`, `status`) USING BTREE,
   INDEX `idx_transaction_id`(`transaction_id`) USING BTREE
 ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
 ​
 SET FOREIGN_KEY_CHECKS = 1;

seata-at.sql:

-- ----------------------------
-- Table structure for undo_log
-- ----------------------------
DROP TABLE IF EXISTS `undo_log`;
CREATE TABLE `undo_log`  (
  `branch_id` bigint(20) NOT NULL COMMENT 'branch transaction id',
  `xid` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'global transaction id',
  `context` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci 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 INDEX `ux_undo_log`(`xid`, `branch_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = 'AT transaction mode undo table' ROW_FORMAT = Compact;
-- ----------------------------
-- Table structure for lock_table
-- ----------------------------
DROP TABLE IF EXISTS `lock_table`;
CREATE TABLE `lock_table`  (
  `row_key` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `xid` varchar(96) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `transaction_id` bigint(20) NULL DEFAULT NULL,
  `branch_id` bigint(20) NOT NULL,
  `resource_id` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `table_name` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `pk` varchar(36) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `gmt_create` datetime NULL DEFAULT NULL,
  `gmt_modified` datetime NULL DEFAULT NULL,
  PRIMARY KEY (`row_key`) USING BTREE,
  INDEX `idx_branch_id`(`branch_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;


SET FOREIGN_KEY_CHECKS = 1;

seata-saga.sql:

-- ----------------------------
-- Table structure for seata_state_inst
-- ----------------------------
DROP TABLE IF EXISTS `seata_state_inst`;
CREATE TABLE `seata_state_inst`  (
  `id` varchar(48) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'id',
  `machine_inst_id` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'state machine instance id',
  `name` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'state name',
  `type` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'state type',
  `service_name` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'service name',
  `service_method` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'method name',
  `service_type` varchar(16) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'service type',
  `business_key` varchar(48) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'business key',
  `state_id_compensated_for` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'state compensated for',
  `state_id_retried_for` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'state retried for',
  `gmt_started` datetime(3) NOT NULL COMMENT 'start time',
  `is_for_update` tinyint(1) NULL DEFAULT NULL COMMENT 'is service for update',
  `input_params` text CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT 'input parameters',
  `output_params` text CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT 'output parameters',
  `status` varchar(2) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'status(SU succeed|FA failed|UN unknown|SK skipped|RU running)',
  `excep` blob NULL COMMENT 'exception',
  `gmt_end` datetime(3) NULL DEFAULT NULL COMMENT 'end time',
  PRIMARY KEY (`id`, `machine_inst_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
-- ----------------------------
-- Table structure for seata_state_machine_def
-- ----------------------------
DROP TABLE IF EXISTS `seata_state_machine_def`;
CREATE TABLE `seata_state_machine_def`  (
  `id` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'id',
  `name` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'name',
  `tenant_id` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'tenant id',
  `app_name` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'application name',
  `type` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'state language type',
  `comment_` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'comment',
  `ver` varchar(16) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'version',
  `gmt_create` datetime(3) NOT NULL COMMENT 'create time',
  `status` varchar(2) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'status(AC:active|IN:inactive)',
  `content` text CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT 'content',
  `recover_strategy` varchar(16) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'transaction recover strategy(compensate|retry)',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

-- ----------------------------
-- Table structure for seata_state_machine_inst
-- ----------------------------
DROP TABLE IF EXISTS `seata_state_machine_inst`;
CREATE TABLE `seata_state_machine_inst`  (
  `id` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'id',
  `machine_id` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'state machine definition id',
  `tenant_id` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'tenant id',
  `parent_id` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'parent id',
  `gmt_started` datetime(3) NOT NULL COMMENT 'start time',
  `business_key` varchar(48) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'business key',
  `start_params` text CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT 'start parameters',
  `gmt_end` datetime(3) NULL DEFAULT NULL COMMENT 'end time',
  `excep` blob NULL COMMENT 'exception',
  `end_params` text CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT 'end parameters',
  `status` varchar(2) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'status(SU succeed|FA failed|UN unknown|SK skipped|RU running)',
  `compensation_status` varchar(2) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'compensation status(SU succeed|FA failed|UN unknown|SK skipped|RU running)',
  `is_running` tinyint(1) NULL DEFAULT NULL COMMENT 'is running(0 no|1 yes)',
  `gmt_updated` datetime(3) NOT NULL,
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE INDEX `unikey_buz_tenant`(`business_key`, `tenant_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

SET FOREIGN_KEY_CHECKS = 1;

6.启动TC服务

进入bin目录,运行其中的seata-server.bat即可:

启动成功后,seata-server应该已经注册到nacos注册中心了。

打开浏览器,访问nacos地址:http://localhost:8848,然后进入服务列表页面,可以看到seata-tc-server的信息:

二、微服务集成seata

1.引入依赖

首先,我们需要在微服务中引入seata依赖:

 <dependency>
     <groupId>com.alibaba.cloud</groupId>
     <artifactId>spring-cloud-starter-alibaba-seata</artifactId>
     <exclusions>
         <!--版本较低,1.3.0,因此排除-->
         <exclusion>
             <artifactId>seata-spring-boot-starter</artifactId>
             <groupId>io.seata</groupId>
         </exclusion>
     </exclusions>
 </dependency>
 <!--seata starter 采用1.4.2版本-->
 <dependency>
     <groupId>io.seata</groupId>
     <artifactId>seata-spring-boot-starter</artifactId>
     <version>${seata.version}</version>
 </dependency>

2.修改配置文件

需要修改application.yml文件,添加一些配置:

 seata:
   registry: # TC服务注册中心的配置,微服务根据这些信息去注册中心获取tc服务地址
     # 参考tc服务自己的registry.conf中的配置
     type: nacos
     nacos: # tc
       server-addr: 127.0.0.1:8848
       namespace: ""
       group: DEFAULT_GROUP
       application: seata-tc-server # tc服务在nacos中的服务名称
       cluster: SH
   tx-service-group: seata-demo # 事务组,根据这个获取tc服务的cluster名称
   service:
     vgroup-mapping: # 事务组与TC服务cluster的映射关系
       seata-demo: SH

三、TC服务的高可用和异地容灾

1.模拟异地容灾的TC集群

计划启动两台seata的tc服务节点:

节点名称

ip地址

端口号

集群名称

seata

127.0.0.1

8091

SH

seata2

127.0.0.1

8092

HZ

之前我们已经启动了一台seata服务,端口是8091,集群名为SH。

现在,将seata目录复制一份,起名为seata2

修改seata2/conf/registry.conf内容如下:

 registry {
   # tc服务的注册中心类,这里选择nacos,也可以是eureka、zookeeper等
   type = "nacos"
 ​
   nacos {
     # seata tc 服务注册到 nacos的服务名称,可以自定义
     application = "seata-tc-server"
     serverAddr = "127.0.0.1:8848"
     group = "DEFAULT_GROUP"
     namespace = ""
     cluster = "HZ"
     username = "nacos"
     password = "nacos"
   }
 }
 ​
 config {
   # 读取tc服务端的配置文件的方式,这里是从nacos配置中心读取,这样如果tc是集群,可以共享配置
   type = "nacos"
   # 配置nacos地址等信息
   nacos {
     serverAddr = "127.0.0.1:8848"
     namespace = ""
     group = "SEATA_GROUP"
     username = "nacos"
     password = "nacos"
     dataId = "seataServer.properties"
   }
 }

进入seata2/bin目录,然后运行命令:

 seata-server.bat -p 8092

打开nacos控制台,查看服务列表:

点进详情查看:

2.将事务组映射配置到nacos

接下来,我们需要将tx-service-group与cluster的映射关系都配置到nacos配置中心。

新建一个配置:

配置的内容如下:

 # 事务组映射关系
 service.vgroupMapping.seata-demo=SH
 ​
 service.enableDegrade=false
 service.disableGlobalTransaction=false
 # 与TC服务的通信配置
 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
 # RM配置
 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
 # TM配置
 client.tm.commitRetryCount=5
 client.tm.rollbackRetryCount=5
 client.tm.defaultGlobalTransactionTimeout=60000
 client.tm.degradeCheck=false
 client.tm.degradeCheckAllowTimes=10
 client.tm.degradeCheckPeriod=2000
 ​
 # undo日志配置
 client.undo.dataValidation=true
 client.undo.logSerialization=jackson
 client.undo.onlyCareUpdateColumns=true
 client.undo.logTable=undo_log
 client.undo.compress.enable=true
 client.undo.compress.type=zip
 client.undo.compress.threshold=64k
 client.log.exceptionRate=100

3.微服务读取nacos配置

接下来,需要修改每一个微服务的application.yml文件,让微服务读取nacos中的client.properties文件:

 seata:
   config:
     type: nacos
     nacos:
       server-addr: 127.0.0.1:8848
       username: nacos
       password: nacos
       group: SEATA_GROUP
       data-id: client.properties

重启微服务,现在微服务到底是连接tc的SH集群,还是tc的HZ集群,都统一由nacos的client.properties来决定了。