Seata1.4.2+Nacos construction and use

Posted by lemist on Wed, 17 Nov 2021 04:08:58 +0100

Seata1.4.2+Nacos construction and use

preface

seata official website
Build environment: mac os
spring-boot.version 2.3.7.RELEASE
spring-cloud-alibaba.version 2.2.2.RELEASE
spring-cloud.version Hoxton.SR9
Database mysql.8.0+

1, Set up seata1.4.2 server

1. Download seata1.4.2

Download address https://github.com/seata/seata/releases

After unpacking and entering the conf folder, you can see that the registry.conf configuration file adds a new dataId configuration compared with the previous version. The original words on the official website are
Since v1.4.2, it has been supported to obtain all configuration information from a Nacos dataId. You only need to add an additional dataId configuration item, so all subsequent configurations are implemented around this method

config {
  # file,nacos ,apollo,zk,consul,etcd3
  type = "file"

  nacos {
    serverAddr = "127.0.0.1:8848"
    namespace = ""
    group = ""
    username = ""
    password = ""
    dataId = "seataServer.properties"  //New configuration,
  }

2. Create relevant databases and tables

Because the store does not use the file mode, but the db mode, the related database and tables are created first
Create database: seata
Create related tables

-- -------------------------------- 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_gmt_modified_status` (`gmt_modified`, `status`),
    KEY `idx_transaction_id` (`transaction_id`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8;

-- 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 = utf8;

-- 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),
    `gmt_create`     DATETIME,
    `gmt_modified`   DATETIME,
    PRIMARY KEY (`row_key`),
    KEY `idx_branch_id` (`branch_id`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8;

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. Configure Seata 1.4.2

In order to distinguish different applications, create a new namespace seata in nacos. The created namespace and namespace id will be used in subsequent configurations

Write the seataServer.properties file configured above in nacos (in order to simply configure the contents of the client, the following clients will share this configuration file, and it is better to configure it separately according to the actual situation)
Write according to the reference configuration file config.txt
https://github.com/seata/seata/blob/develop/script/config-center/config.txt

transport.type=TCP
transport.server=NIO
transport.heartbeat=true
transport.enableClientBatchSendRequest=true
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
# server
server.recovery.committingRetryPeriod=1000
server.recovery.asynCommittingRetryPeriod=1000
server.recovery.rollbackingRetryPeriod=1000
server.recovery.timeoutRetryPeriod=1000
server.undo.logSaveDays=7
server.undo.logDeletePeriod=86400000
server.maxCommitRetryTimeout=-1
server.maxRollbackRetryTimeout=-1
server.rollbackRetryTimeoutUnlockEnable=false
server.distributedLockExpireTime=10000
# store
#Change model to db
store.mode=db
store.lock.mode=file
store.session.mode=file
# store.publicKey=""
store.file.dir=file_store/data
store.file.maxBranchSessionSize=16384
store.file.maxGlobalSessionSize=512
store.file.fileWriteBufferCacheSize=16384
store.file.flushDiskMode=async
store.file.sessionReloadReadSize=100
store.db.datasource=druid
store.db.dbType=mysql
#Modify the data driver. This is mysql8. If you use mysql5, please modify it
store.db.driverClassName=com.mysql.cj.jdbc.Driver
# Change to the seata service database created above
store.db.url=jdbc:mysql://127.0.0.1:3306/seata?useUnicode=true&rewriteBatchedStatements=true
# Change to your own database user name
store.db.user=root
# Change your database password
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
store.redis.mode=single
store.redis.single.host=127.0.0.1
store.redis.single.port=6379
# store.redis.sentinel.masterName=""
# store.redis.sentinel.sentinelHosts=""
store.redis.maxConn=10
store.redis.minConn=1
store.redis.maxTotal=100
store.redis.database=0
# store.redis.password=""
store.redis.queryLimit=100
# log
log.exceptionRate=100
# metrics
metrics.enabled=false
metrics.registryType=compact
metrics.exporterList=prometheus
metrics.exporterPrometheusPort=9898
# service
# Name yourself a vgroupMapping
service.vgroupMapping.fsp_tx_group=default
service.default.grouplist=127.0.0.1:8091
service.enableDegrade=false
service.disableGlobalTransaction=false
# 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=false
client.rm.tableMetaCheckerInterval=60000
client.rm.sqlParserType=druid
client.rm.reportSuccessEnable=false
client.rm.sagaBranchRegisterEnable=false
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
client.undo.logTable=undo_log
client.undo.compress.enable=true
client.undo.compress.type=zip
client.undo.compress.threshold=64k

registry {
  # file ,nacos ,eureka,redis,zk,consul,etcd3,sofa
  type = "nacos"  #Change to nacos

  nacos {
    application = "seata-server"  
    serverAddr = "localhost:8848"  #Change to your own nacos address
    group = "SEATA_GROUP"  #Change to your own group
    namespace = "ef11b50a-4d85-48a3-9096-ab4c87df509f"  #Change to your own nacos namespace. Fill in the id of the seata namespace just created
    cluster = "default" 
    username = "nacos" #Change to your own nacos user name
    password = "nacos" #Change to your own nacos password
  }

config {
  # file,nacos ,apollo,zk,consul,etcd3
  type = "nacos" #Change to nacos

  nacos {
    serverAddr = "localhost:8848" #Change to your own nacos address
    namespace = "ef11b50a-4d85-48a3-9096-ab4c87df509f" #Change to your own nacos namespace. Fill in the id of the seata namespace just created
    group = "SEATA_GROUP"
    username = "nacos" #Change to your own nacos user name
    password = "nacos" #Change to your own nacos password
    dataId = "seataServer.properties" #Change to your own configuration file dataId. The default is used here
  }

4. Start seata1.4.2

2, The client uses seata1.4.2

1. Preparation

Create tables in the database of each microservice

-- 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 = InnoDB
  AUTO_INCREMENT = 1
  DEFAULT CHARSET = utf8 COMMENT ='AT transaction mode undo table';
  

2. Test seata1.4.2

The dependency is introduced into the pom file. Note that the version of introducing seata must be consistent with the version of seata server

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-seata</artifactId>
    <exclusions>
        <!-- To be with seata Server version always,So replace your own -->
        <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>1.4.2</version>
</dependency>

Writing yml configuration files

seata:
    #The transaction group (each application can be named independently or use the same name) should be the same as the service.vgroup in the server nacos-config.txt_ Mapping exists, and the suffix names of multiple groups should be consistent -tx_group
    enabled: true
    enable-auto-data-source-proxy: true #Whether to enable data source automatic proxy. The default value is true
    tx-service-group: fsp_tx_group  #To be consistent with vgroupMapping in the configuration file
    registry:  #Registry is configured according to registry of seata server
        type: nacos #The default is file
        nacos:
            application: seata-server #Configure your own seata service
            server-addr: ${spring.cloud.nacos.discovery.server-addr} #According to your own seata service configuration
            username: nacos #According to your own seata service configuration
            password: nacos #According to your own seata service configuration
            cluster: default # Configure your own seata service cluster. The default value is default
            group: SEATA_GROUP #According to your own seata service configuration
            namespace: ef11b50a-4d85-48a3-9096-ab4c87df509f ##Change to your own nacos namespace. Fill in the id of the seata namespace just created
    config:
        type: nacos #The default is file. If file is used instead of configuring the following nacos, configure seata.service directly
        nacos:
            server-addr: ${spring.cloud.nacos.discovery.server-addr} #Configure your own nacos address
            group: SEATA_GROUP #Configure your own dev
            username: nacos #Configure your own username
            password: nacos #Configure your own password
            dataId: seataServer.properties # #Configure your own dataId. Since the client configuration is also written in seataServer.properties when building the server, the same configuration file as the server is used here. It is better to separate the configuration files of the actual client and the server
            namespace: ef11b50a-4d85-48a3-9096-ab4c87df509f @#Change to your own nacos namespace. Fill in the id of the seata namespace just created

If the server configuration file does not write the client configuration when building the server, you need to write the dataId file (client configuration file) of seata configuration in the previous step in nacos. In this example, you do not need to write the client seata configuration file separately

Add annotation @ EnableAutoDataSourceProxy on startup class

//After version 1.1 of seata, the DataSourceProxy is enabled with annotations. In previous versions, the DataSourceProxy configuration needs to be written manually to enable seata to manage the database
@EnableAutoDataSourceProxy 

All transaction related microservices are configured as above
Add the annotation @ GlobalTransactional on the method initiated by the transaction

//seata transaction control annotation. name is customized to ensure uniqueness
@GlobalTransactional(name = "save-funds", rollbackFor = Exception.class) 
public Boolean saveFundsRevise(FundsRevise fundsRevise){
	//Business logic
}

3. Test results

Start the project, and you can see the related microservices and corresponding databases in the seata log

Initiate a request to execute a transaction. You can see the relevant rollback log records in the seata log, and view the database data. The rollback is successful

summary

Note that if you modify the seata server configuration, be sure to restart it
Reference blog
Seata1.4.2+Nacos construction and use https://blog.csdn.net/ww_run/article/details/120099870

Topics: Java Linux Spring Boot Software seata