SpringBoot integration springcloud Alibaba Seata details

SpringCloud Alibab-Seata Introduction:

Seata is an open source distributed transaction solution, which is committed to providing high-performance and easy-to-use distributed transaction services under the microservice architecture.

Seata will provide users with AT, TCC, SAGA and XA transaction modes to create a one-stop distributed solution for users.

The original Fescar is a distributed transaction solution.

Detailed introduction, which can be read Springcloud Alibaba Seata official website

1, SpringBoot integrates Seata

1. Pre requirements

Before integrating Seata, the following pre requirements must be made:

1. Create table undo_log

  • SEATA AT mode requires that the database table corresponding to each micro service must be created first_ Log (rollback record table)

    – note here 0.3.0+ add unique index ux_undo_log
    CREATE TABLE undo_log (
    id bigint(20) NOT NULL AUTO_INCREMENT,
    branch_id bigint(20) NOT NULL,
    xid varchar(100) NOT NULL,
    context varchar(128) NOT NULL,
    rollback_info longblob NOT NULL,
    log_status int(11) NOT NULL,
    log_created datetime NOT NULL,
    log_modified datetime NOT NULL,
    ext varchar(100) DEFAULT NULL,
    PRIMARY KEY (id),
    UNIQUE KEY ux_undo_log (xid,branch_id)
    ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

2. Install Transaction Coordinator (Seata server)

Download and install the latest version of the transaction coordinator (Seata server).

  • Download Seata server v1.5.1, GitHub download address
  • Execute the startup file under /conf directory and start normally.

2. Import dependency

 <!--Seata (Distributed transaction solution)-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-seata</artifactId>
     <!-- according to spring-cloud-alibaba Version customized import the corresponding version of seata rely on -->
    <version>${spring-cloud-alibaba.version}</version>
</dependency>
 <!--If you want to upgrade separately seata The latest version is used and can be imported by yourself seata Core package-->
<dependency>
    <groupId>io.seata</groupId>
    <artifactId>seata-spring-boot-starter</artifactId>
    <version>1.5.1</version>
</dependency>

maven dependency diagram is as follows:

3. Add Seata configuration

Scheme 1: file conf + registry. Conf (original configuration)

  • By default, the configuration mode of seata is file, which can be read from file. seata also provides other configuration modes, such as putting them into configuration centers such as Nacos and Apollo.

    • The default file configuration mode is explained below. If you need to use the configuration center mode, please extract it to the configuration center by yourself:

      1. Set file Add the conf file to the /resources configuration path, which is at the same level as application.yml.

      2. Set registry Add the conf file to the /resources configuration path, which is at the same level as application.yml.

file.conf example

For the latest sample configuration, please refer to the official documentation. This example is copied from v1.5.0 - v1.5.1 seata conf configuration file address .

  • Here, focus on service.vgroupmapping default_tx_group = "default" configuration, default_tx_group is the default transaction group name in v1.5.1. If you want to customize this transaction group name, you can configure seata.tx-service-group=default_tx_group customization.
  • If not, Seata server will not be registered when the client starts, and the console will report an error can not get cluster name in registry config'service.vgroupmapping default_ tx_ group', please make sure registry config correct.
transport {
  # tcp udt unix-domain-socket
  type = "TCP"
  #NIO NATIVE
  server = "NIO"
  #enable heartbeat
  heartbeat = true
  # the client batch send request enable
  enableClientBatchSendRequest = true
  #thread factory for netty
  threadFactory {
    bossThreadPrefix = "NettyBoss"
    workerThreadPrefix = "NettyServerNIOWorker"
    serverExecutorThread-prefix = "NettyServerBizHandler"
    shareBossWorker = false
    clientSelectorThreadPrefix = "NettyClientSelector"
    clientSelectorThreadSize = 1
    clientWorkerThreadPrefix = "NettyClientWorkerThread"
    # netty boss thread size,will not be used for UDT
    bossThreadSize = 1
    #auto default pin or 8
    workerThreadSize = "default"
  }
  shutdown {
    # when destroy server, wait seconds
    wait = 3
  }
  serialization = "seata"
  compressor = "none"
}
service {
  #transaction service group mapping
  vgroupMapping.default_tx_group = "default"
  #only support when registry.type=file, please don't set multiple addresses
  default.grouplist = "127.0.0.1:8091"
  #degrade, current not support
  enableDegrade = false
  #disable seata
  disableGlobalTransaction = false
}

client {
  rm {
    asyncCommitBufferLimit = 10000
    lock {
      retryInterval = 10
      retryTimes = 30
      retryPolicyBranchRollbackOnConflict = true
    }
    reportRetryCount = 5
    tableMetaCheckEnable = false
    reportSuccessEnable = false
  }
  tm {
    commitRetryCount = 5
    rollbackRetryCount = 5
  }
  undo {
    dataValidation = true
    logSerialization = "jackson"
    logTable = "undo_log"
  }
  log {
    exceptionRate = 100
  }
}

registry.conf example

For the latest sample configuration, please refer to the official documentation. This example is copied from v1.5.0 - v1.5.1 seata conf configuration file address .

registry {
  # file ,nacos ,eureka,redis,zk,consul,etcd3,sofa
  # Specify the registration type. Here, use the file file to read the configuration mode. If you use the 'nacos' configuration center, modify the corresponding' naocs' configuration (don't forget to migrate the current configuration file to the configuration center)
  type = "file"

  nacos {
	application = "seata-server"
    serverAddr = "127.0.0.1:8848"
    group = "SEATA_GROUP"
    namespace = ""
    cluster = "default"
    username = "nacos"
    password = "nacos"
  }
  eureka {
    serviceUrl = "http://localhost:8761/eureka"
    application = "default"
    weight = "1"
  }
  redis {
    serverAddr = "localhost:6379"
    db = 0
    password = ""
    cluster = "default"
    timeout = 0
  }
  zk {
    cluster = "default"
    serverAddr = "127.0.0.1:2181"
    sessionTimeout = 6000
    connectTimeout = 2000
    username = ""
    password = ""
  }
  consul {
    cluster = "default"
    serverAddr = "127.0.0.1:8500"
  }
  etcd3 {
    cluster = "default"
    serverAddr = "http://localhost:2379"
  }
  sofa {
    serverAddr = "127.0.0.1:9603"
    application = "default"
    region = "DEFAULT_ZONE"
    datacenter = "DefaultDataCenter"
    cluster = "default"
    group = "SEATA_GROUP"
    addressWaitTime = "3000"
  }
  file {
    name = "file.conf"
  }
}

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

  nacos {
    serverAddr = "127.0.0.1:8848"
    namespace = ""
    group = "SEATA_GROUP"
    username = "nacos"
    password = "nacos"
    dataId = "seataServer.properties"
  }
  consul {
    serverAddr = "127.0.0.1:8500"
  }
  apollo {
    appId = "seata-server"
    apolloMeta = "http://192.168.1.204:8801"
    namespace = "application"
  }
  zk {
    serverAddr = "127.0.0.1:2181"
    sessionTimeout = 6000
    connectTimeout = 2000
    username = ""
    password = ""
  }
  etcd3 {
    serverAddr = "http://localhost:2379"
  }
  file {
    name = "file.conf"
  }
}

application.yml

When a higher version of Springboot is started, the console may report a circular dependency error of com.alibaba.cloud.seata.rest.SeataRestTemplateAutoConfiguration. You need to configure spring.main.allow-circular-references=true to allow circular dependencies.

spring:
  application:
    name: seata-test
  main:
    # Circular dependency is allowed to avoid the error of "com.alibaba.cloud.seata.rest.SeataRestTemplateAutoConfiguration" circular dependency at startup
    allow-circular-references: true
server:
  port: 9000

# Default configuration of seata transaction group (solve the problem of invalid configuration of v1.5.1 version)
seata:
  tx-service-group: default_tx_group # You can customize the transaction group name, "default_tx_group" is the default value. If you change it here, file Conf configuration `server.vgroupmapping XXXX ` should also be changed together, otherwise it will not register "Seata server" and cause an error.
logging:
  level:
    io.seata: debug

Scheme 2: integrate seata configuration into application In the YML file

Equivalent to file conf + registry. Conf, integrated into application.yml.

####################################################################################################
# Seata configuration
seata:
  enabled: true # Default on
  application-id: ${spring.application.name}
  tx-service-group: default_tx_group # Transaction group (each application can be named independently or use the same name)
  client:
    rm-report-success-enable: true
    rm-table-meta-check-enable: false # Automatically refresh the table structure in the cache (false by default)
    rm-report-retry-count: 5 # TC retry times of phase I result reporting (default 5)
    rm-async-commit-buffer-limit: 10000 # Asynchronous commit cache queue length (default 10000)
    rm:
      lock:
        lock-retry-internal: 10 # Verify or occupy global lock retry interval (default 10ms)
        lock-retry-times: 30 # Retry times of verifying or occupying global lock (default 30)
        lock-retry-policy-branch-rollback-on-conflict: true # Lock policy when branch transactions conflict with other global rollback transactions (give priority to releasing local locks to make rollback successful)
    tm-commit-retry-count: 3 # The number of TC retries for submitting the results of the global submission in the first stage (1 by default, it is recommended to be greater than 1)
    tm-rollback-retry-count: 3 # The number of TC retries reported by the global rollback results in the first stage (1 by default, it is recommended to be greater than 1)
    undo:
      undo-data-validation: true # Two stage rollback image verification (true by default)
      undo-log-serialization: jackson # undo serialization method (default jackson)
      undo-log-table: undo_log  # User defined undo table name (default undo_log)
    log:
      exception-rate: 100 # Log abnormal output probability (default 100)
    support:
      spring:
        datasource-autoproxy: true
  service:
    vgroup-mapping:
      default_tx_group: default # TC cluster (must be consistent with Seata server)
    grouplist:
      default: 127.0.0.1:8091
    enable-degrade: false # Degraded switch
    disable-global-transaction: false # Disable global transactions (default false)

  transport:
    type: TCP
    server: NIO
    heartbeat: true
    serialization: seata
    compressor: none
    enable-client-batch-send-request: true # Whether the client transaction message request is sent in batches (default true)
    shutdown:
      wait: 3
    thread-factory:
      boss-thread-prefix: NettyBoss
      worker-thread-prefix: NettyServerNIOWorker
      server-executor-thread-prefix: NettyServerBizHandler
      share-boss-worker: false
      client-selector-thread-prefix: NettyClientSelector
      client-selector-thread-size: 1
      client-worker-thread-prefix: NettyClientWorkerThread

  registry:
    type: file  # file ,nacos ,eureka,redis,zk,consul,etcd3,sofa
  config:
    #    file:
    #      name: file.conf
    type: file  # file,nacos ,apollo,zk,consul,etcd3
####################################################################################################

Scheme 3: seata client configuration is integrated into the configuration center:

  • Briefly, take Nacos as an example. For details, see "FAQ question 1 scheme 2" below.

Read configuration source code analysis:

ConfigurationFactory

public final class ConfigurationFactory {
    
    private static Configuration buildConfiguration() {
        //1. Get 'config.type' configuration type
        String configTypeName = CURRENT_FILE_INSTANCE.getConfig(
                ConfigurationKeys.FILE_ROOT_CONFIG + ConfigurationKeys.FILE_CONFIG_SPLIT_CHAR
                        + ConfigurationKeys.FILE_ROOT_TYPE);
        //Slightly....
        
        //2. File type (read configuration in local file mode)
        if (ConfigType.File == configType) {
            String pathDataId = String.join(ConfigurationKeys.FILE_CONFIG_SPLIT_CHAR,
                    ConfigurationKeys.FILE_ROOT_CONFIG, FILE_TYPE, NAME_KEY);
            String name = CURRENT_FILE_INSTANCE.getConfig(pathDataId);
            configuration = new FileConfiguration(name);
            try {
                //2.1 'extconfigurationprovider' interface, the only implementation class' SpringBootConfigurationProvider '`
                extConfiguration = EnhancedServiceLoader.load(ExtConfigurationProvider.class).provide(configuration);
               //Slightly
            }
            //Slightly
        } else {
          
            //3. Other types of read configuration come here
            //3.1 the 'configurationprovider' interface has many implementation classes, such as Nacos, apollo and other configuration centers
            configuration = EnhancedServiceLoader
                    .load(ConfigurationProvider.class, Objects.requireNonNull(configType).name()).provide();
        }
        //Slightly... Not the point
        return null == extConfiguration ? configuration : extConfiguration;
    }
}

Implementation class of ExtConfigurationProvider interface:

Implementation class of ConfigurationProvider interface:

Take Nacos as an example. If the configuration read by seata.config.nacos.data-id is not empty, add a listener to specifically listen for changes to the configuration.

4. Set the DataSourceProxy of seata as the main data source and wrap the original DataSource data source, otherwise the transaction cannot be rolled back

  • After the spring cloud starter Alibaba Seata dependency is introduced, io.seata.spring.boot.autoconfigure.SeataDataSourceAutoConfiguration has been automatically injected for us.

Source code analysis:

SeataDataSourceAutoConfiguration
@ConditionalOnBean({DataSource.class})
@ConditionalOnExpression("${seata.enabled:true} && ${seata.enableAutoDataSourceProxy:true} && ${seata.enable-auto-data-source-proxy:true}")
@AutoConfigureAfter({SeataCoreAutoConfiguration.class})
public class SeataDataSourceAutoConfiguration {
    public SeataDataSourceAutoConfiguration() {
    }

    @Bean({"seataAutoDataSourceProxyCreator"})
    @ConditionalOnMissingBean({SeataAutoDataSourceProxyCreator.class})//If this class' SeataAutoDataSourceProxyCreator 'is missing, it will be injected automatically.
    public SeataAutoDataSourceProxyCreator seataAutoDataSourceProxyCreator(SeataProperties seataProperties) {
        //[key] this class' SeataAutoDataSourceProxyCreator 'helps me encapsulate DataSource processing.
        //seataProperties.getDataSourceProxyMode(): the "AT" mode is used by default
        return new SeataAutoDataSourceProxyCreator(seataProperties.isUseJdkProxy(), seataProperties.getExcludesForAutoProxying(), seataProperties.getDataSourceProxyMode());
    }
}
SeataAutoDataSourceProxyCreator
import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import io.seata.core.model.BranchType;
import io.seata.rm.datasource.DataSourceProxy;
import io.seata.rm.datasource.SeataDataSourceProxy;
import io.seata.rm.datasource.xa.DataSourceProxyXA;
import org.aopalliance.aop.Advice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.TargetSource;
import org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator;
import org.springframework.aop.support.DefaultIntroductionAdvisor;
public class SeataAutoDataSourceProxyCreator extends AbstractAutoProxyCreator {
	//Other codes are omitted.

    SeataDataSourceProxy buildProxy(DataSource origin, String proxyMode) {
      
        if (BranchType.AT.name().equalsIgnoreCase(proxyMode)) {
            //Give DataSource to DataSourceProxy proxy of seata
            return new DataSourceProxy(origin);
        }
        if (BranchType.XA.name().equalsIgnoreCase(proxyMode)) {
             //Give DataSource to DataSourceProxy proxy of seata
            return new DataSourceProxyXA(origin);
        }
        throw new IllegalArgumentException("Unknown dataSourceProxyMode: " + proxyMode);
    }
}

5. Microservices can be started and distributed transactions can be tested

1. Mark the entry of distributed large transactions with @GlobalTransactional, and the effect can be simply understood as the same as that of @Transactional provided by Spring. The difference is that seata's @GlobalTransactional annotation uses the AT mode by default to control distributed transactions through the 2PC model. (of course, the premise is that seata is also introduced into other micro services, and repeat steps 1-2 above.)

2. The methods of other microservice methods called remotely normally use the @Transactional annotation, which means that they control their own transactions. It does not conflict with the @GlobalTransactional annotation and should be used at the same time.

Test project, with official subproject springcloud-nacos-seata For example:

  • When there is a transaction to be recorded, it will be recorded in the undo of the corresponding database_ Log table, add a new record.

  • Seata server console global transaction log printing. You can see the "AT mode" in the figure, which automatically controls the submission and rollback of global transactions.

2, FAQ

Problem 1. Seata starts with an error can not get cluster name in registry config'service.vgroupmapping default_ tx_ group', please make sure registry config correct

When learning to use it today, I found that the console kept reporting an error can not get cluster name in registry config'service.vgroupmapping default_ tx_ Group', please make sure registry config correct, the problem solving process is recorded as follows:

Server Seata server version: 1.5.1

Client Seata spring boot starter version: 1.5.1

Recurrence:

  1. After downloading the latest Seata server 1.5.1, unzip it and modify the application The YML configuration file is in the nacos mode, then execute the startup file (in the installation directory inseata-server.bat), and double-click to directly start the server.

  2. The client starts after importing the Seata spring boot starter dependency, and the console frantically reports errors. can not get cluster name in registry config 'service.vgroupMapping.default_tx_group', please make sure registry config correct

(if the problem is reported when deploying to Linux system, it is the same reason)

solve:

Later, debug checked the source code and found that I set registry in the application.yml configuration file Type=nacos and config Type=nacos, which means: read the seata configuration of the Nacos configuration center. But the Nacos configuration center did not add file The configuration of conf and registry.conf leads to

I think the Seata server directory of V1.5.1 is d:seata-server-1.5.1seataconapplication YML configuration file configuration, there is no need to configure in Nacos. After all, they are so similar... However, it is not. One is the configuration of the server (Seata server) and the other is the configuration of the client (microservice). Here is a record to avoid forgetting.

Scheme 1: get the configuration from the file configuration instead

  1. Modify the configuration: registry Type=file and config Type=file, which means to obtain the configuration from the file configuration.
  2. Then, the client adds file Conf and registry Conf configuration, as shown in the following figure:

Version 1.5.0 ~ 1.5.1 about (seata/script/client/conf/) configuration address

Scheme 2: "configuration center reading method" has a pit: in addition to adding custom seata In addition to the properties configuration file, you need to add an additional DataId of service.vgroupMapping.default_tx_group, with the value of default.

For example, Nacos configuration center, Nacos' configuration of Seata client, as shown in the following figure:
  1. service.vgroupMapping.default_tx_group . This configuration is because the RegistryService class creates a key of service.vgroupmapping default_ tx_ The listener of Group monitors this attribute. If it is not added, the console will report an error can not get cluster name in registry config'service.vgroupmapping default_ tx_ group', please make sure registry config correct
  2. seata-clien-file-conf.yml (equivalent to migrating the file.conf file to the configuration center.)

application.yml (equivalent to integrating the configuration of the registry.conf configuration file here)
# Seata registry. Configuration of conf configuration file
seata:
  enabled: true # Enabled by default (this value is useless even if it is assigned to the configuration center, so it is put here)
  application-id: ${spring.application.name}  #  (it's useless to assign this value to the configuration center, so put it here)
  tx-service-group: default_tx_group # Transaction group (each application can be named independently or use the same name)
  registry:
    type: nacos  # file ,nacos ,eureka,redis,zk,consul,etcd3,sofa
    nacos:
      server-addr: localhost:8848
      namespace: ee49309e-3d4b-431a-a8e6-06a7538dc95f
      cluster: default
      group: SEATA_GROUP
      username: nacos
      password: nacos

  config:
    type: nacos  # file,nacos ,apollo,zk,consul,etcd3
    nacos:
      namespace: ee49309e-3d4b-431a-a8e6-06a7538dc95f   # Configuration center namespace unique id
      server-addr: localhost:8848
      group: SEATA_GROUP   # Nacos grouping, Seata by default_ Group, note: the default group of Nacos is DEFAULT_GROP
      username: nacos
      password: nacos
      data-id:  seata-clien-file-conf.yml   # Custom read configuration name, default seata.properties
Seata-clien-file-conf.yml (equivalent to file.conf configuration file)
# Seata file. Configuration of conf configuration file
seata:
  client:
    rm-report-success-enable: true
    rm-table-meta-check-enable: false # Automatically refresh the table structure in the cache (false by default)
    rm-report-retry-count: 5 # TC retry times of phase I result reporting (default 5)
    rm-async-commit-buffer-limit: 10000 # Asynchronous commit cache queue length (default 10000)
    rm:
      lock:
        lock-retry-internal: 10 # Verify or occupy global lock retry interval (default 10ms)
        lock-retry-times: 30 # Retry times of verifying or occupying global lock (default 30)
        lock-retry-policy-branch-rollback-on-conflict: true # Lock policy when branch transactions conflict with other global rollback transactions (give priority to releasing local locks to make rollback successful)
    tm-commit-retry-count: 3 # The number of TC retries for submitting the results of the global submission in the first stage (1 by default, it is recommended to be greater than 1)
    tm-rollback-retry-count: 3 # The number of TC retries reported by the global rollback results in the first stage (1 by default, it is recommended to be greater than 1)
    undo:
      undo-data-validation: true # Two stage rollback image verification (true by default)
      undo-log-serialization: jackson # undo serialization method (default jackson)
      undo-log-table: undo_log  # User defined undo table name (default undo_log)
    log:
      exception-rate: 100 # Log abnormal output probability (default 100)
    support:
      spring:
        datasource-autoproxy: true
  service:
    vgroup-mapping:
      default_tx_group: default # TC cluster (must be consistent with Seata server)
    grouplist:
      default: 127.0.0.1:8091
    enable-degrade: false # Degraded switch
    disable-global-transaction: false # Disable global transactions (default false)

  transport:
    type: TCP
    server: NIO
    heartbeat: true
    serialization: seata
    compressor: none
    enable-client-batch-send-request: true # Whether the client transaction message request is sent in batches (default true)
    shutdown:
      wait: 3
    thread-factory:
      boss-thread-prefix: NettyBoss
      worker-thread-prefix: NettyServerNIOWorker
      server-executor-thread-prefix: NettyServerBizHandler
      share-boss-worker: false
      client-selector-thread-prefix: NettyClientSelector
      client-selector-thread-size: 1
      client-worker-thread-prefix: NettyClientWorkerThread

Successfully resolved

  • seata server 1.5.1 the content printed on the server console is as follows, indicating that the "XXX order" service has been successfully registered with seata. After the operation is stable, the client control does not report errors anymore, and it is successful.

Pit during solution:

  1. The official documents only have a general description of the use effect, and the specific details depend on the code of the "sub project".
  2. During this period, I checked and read the official website Version upgrade Guide , upgrading from v1.4.x to v1.5.x does not involve the change of this problem, and the answer to this problem is not found.
  3. At first, I downloaded the latest version of v1.5.1, Seata server. Then it was fooled by the installation directory. The following is a comparison of the conf directories of v1.5.1 and v1.4.2.
  4. Reluctantly, go to github to find the official Sample code subproject (Seata samples) , read the instructions carefully and ran the project.
  5. The configuration file of each subproject will have "file.conf" and "registry.conf" configuration files. It was later learned that these projects used registry Type=file and config Type=file get the configuration by reading the configuration from the local file (that is, scheme 1 above).

Summary:

  • Obviously, v1.4.2 uses the configuration obtained from "local file reading (file.conf and registry.conf)". In fact, many of the parameters configured in this way do not need to be changed, or ordinary people will not easily change them;

  • One of the optimizations in v1.5.1 should be to optimize file Conf and registry Conf, and then integrated into application.yml to hide most parameters that will not be changed (using the default configuration).

  • Because this configuration is placed in application The configuration in YML is similar to file Conf and registry Conf configuration is very similar, which leads me to the illusion that if the server is configured, the client does not need to configure file Conf and registry Conf, and then it's not. Seata server is the server, the server is the server, and the client is the client. The configurations on both sides are separate and need to be added.

  • The solution to this problem is to "add seata configuration (file.conf and registry.conf)".

Question 2. After integrating Seata, SpringBoot finds that distributed transactions do not work?

Please check the following conditions in order.

1. Check whether the dependency is introduced correctly It is not enough to import only the Seata spring boot starter dependency.

  • It is not enough to import Seata spring boot starter dependency only

  • You also need to import the spring boot starter AOP dependency. org.aspectj:aspectjweaver is introduced internally

    It is recommended to introduce dependency as follows:

    com.alibaba.cloud spring-cloud-starter-alibaba-seata ${spring-cloud-alibaba.version} io.seata seata-spring-boot-starter 1.5.1

Dependency graph:

2. If it is "how to read configuration from files (registry.type=file and config.type=file)", check whether the configuration file is loaded in the classes directory.

As shown in the following figure:

3. Does the @GlobalTransactional annotation work?

  1. Check seata Set the enabled attribute to true to open the Seata distributed transaction.

  2. @GlobalTransactional is added to the entry method of large transactions. For example, the method of service A calls the method of service B, C and D. Then the @GlobalTransactional annotation should be added to the xxxserviceimpl method of service A, not to the remotely invoked B, C, and D services.

  3. @The GlobalTransactional annotation is no problem, but whether the remote calling microservices involved have introduced seata dependency. Whether the microservices involved (B, C, D) are normally registered with the seata server transaction coordinator?

    • If you register normally, the Seata server console will print: TM register success,message:RegisterTMRequest{applicationId='your service name'... Omitted};
    • RM register success, message:registerrmrrequest{resourceids='jdbc: mysql://ip:3306/ Database name ', applicationId=' your service name '... Omitted}
  4. Each service needs to use seata's repeated troubleshooting of 1-3 problems, which can generally be solved.

3, Seata AT mode solves the disadvantages of distributed transactions

By default, Seata uses "AT mode" to solve distributed transactions, which is actually "2PC mode". Because AT mode is based on global transactions and a global lock, it is not suitable for high concurrency scenarios.

Seata also supports "TCC mode" and "saga mode". Although the number of concurrency is improved compared with that of AT mode, it is not suitable for high concurrency scenarios.

High concurrency scenarios will eventually have to be solved by "flexible transactions - best effort notification scheme" or "flexible transactions - reliable messages + final consistency scheme (asynchronous guaranteed)".

4, Related links:

First of all, I would like to introduce myself. I graduated from Jiaotong University in 13 years. I once worked in a small company, went to large factories such as Huawei OPPO, and joined Alibaba in 18 years, until now. I know that most junior and intermediate Java engineers who want to improve their skills often need to explore and grow by themselves or sign up for classes, but there is a lot of pressure on training institutions to pay nearly 10000 yuan in tuition fees. The self-study efficiency of their own fragmentation is very low and long, and it is easy to encounter the ceiling technology to stop. Therefore, I collected a "full set of learning materials for java development" and gave it to you. The original intention is also very simple. I hope to help friends who want to learn by themselves and don't know where to start, and reduce everyone's burden at the same time. Add the business card below to get a full set of learning materials

Tags: Front-end Android Back-end Interview

Posted by kporter.porter on Sun, 31 Jul 2022 21:07:19 +0300