Architecture design | based on Seata middleware, transaction management under microservice mode

Source address: GitHub · click here || GitEE · point here

1, Introduction to Seata

1. Seata assembly

Seata is an open source distributed transaction solution, which is committed to providing high-performance and easy-to-use distributed transaction services. Seata will provide users with AT, TCC, SAGA and XA transaction modes to create a one-stop distributed solution for users.

2. Support mode

AT mode

  • Based on a relational database that supports local ACID transactions.
  • Java application, accessing the database through JDBC.

Phase I: the business data and rollback log records are committed in the same local transaction, and the local lock and connection resources are released.

Phase 2: asynchronous submission, very fast completion. Rollback is compensated in reverse through the rollback log of one stage.

TCC mode

A distributed global transaction is a two-stage commit model as a whole. The global transaction is composed of several branch transactions. The branch transactions should meet the requirements of the two-stage commit model, that is, each branch transaction needs to have its own:

prepare phase I behavior

Two stage commit or rollback behavior

Saga mode

Saga mode is a long transaction solution provided by SEATA. In Saga mode, each participant in the business process submits a local transaction. When a participant fails, the previous successful participants will be compensated. The phase I forward service and phase II compensation service are implemented by business development.

XA mode

Xa is a distributed transaction protocol, which is a non intrusive distributed transaction solution for business. XA submission protocol requires the database support of transaction participants. XA transactions have strong consistency. In the whole process of two-stage submission, they will always hold the lock of resources, and the disadvantage of poor performance is obvious.

2, Server deployment

1. Download component package

Version 1.2: seata-server-1.2.0 zip

Unzip directory

  • bin: store the startup script of the server;
  • lib: store the resource jar package that the server depends on;
  • conf: configuration file directory.

2. Modify configuration

file.conf configuration

mode:db uses the database to store transaction information. Here, you can also choose the file storage method.

File mode is stand-alone mode. The global transaction session information is read and written in memory and the local file root is persisted Data, high performance;

The db mode is highly available. The global transaction session information is shared through db, and the corresponding performance is worse;

The redis mode is supported by Seata server version 1.3 and above, with high performance and the risk of loss of transaction information. Please configure the redis persistence configuration suitable for the current scenario in advance

store {
  ## store mode: file,db
  mode = "db"
  db {
    datasource = "druid"
    dbType = "mysql"
    driverClassName = "com.mysql.jdbc.Driver"
    url = "jdbc:mysql://"
    user = "root"
    password = "123456"
    minConn = 5
    maxConn = 30
    globalTable = "global_table"
    branchTable = "branch_table"
    lockTable = "lock_table"
    queryLimit = 100
    maxWait = 5000

registry.conf configuration

Here, eureka is selected as the registration center, and Seata server is also added to the registration center as a service. The configuration center is not used, so the config configuration can be configured by default.

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

  eureka {
    serviceUrl = "http://localhost:8761/eureka"
    application = "default"
    weight = "1"

3. Transaction management table

Three transaction management tables need to be established in Seata server, the MySQL database configured above:

  • Global transaction: global_table
  • Branch transaction: branch_table
  • Global lock: lock_table
  • Transaction rollback: undo_log
  • SQL script: MySQL script directory

4. Start command

Linux environment: SH Seata server sh

3, Business service construction

1. Code structure

  • Seata Eureka: Registry
  • Seata order: order service
  • Seata account: Account Service
  • Seata inventor: inventory service
  • Seata client: client service
  • Account Feign: account Feign interface
  • Inventory Feign: inventory Feign interface
  • Order Feign: order Feign interface

Request link: client - > order - > account + inventory, test the distributed transaction problem of the whole process.

2. Database structure

  • seata_server: Seata component server dependent Library
  • seata_account: simulated account database
  • seata_inventor: simulated inventory database
  • seata_order: simulated order database

Script location of each library: MySQL script / data biz sql

3. Start service

Start in sequence: Registration Center, inventory service, account service, order service and client service;

Eureka services are listed below:

4, Seata usage details

1. Seata basic configuration

Several basic services are configured in the same way.

conf configuration

file.conf focuses on the following contents. The name of the transaction group needs to be used in the yml file.

my_test_tx_group = "default"

registry.conf: is the choice of the registry.

2. Database configuration

Note the transaction group name configuration here.

  # Name of the transaction group
        tx-service-group: my_test_tx_group
  # Data source configuration
      driverClassName: com.mysql.jdbc.Driver
      url: jdbc:mysql://
      username: root
      password: 123456

The whole database is managed by Seata agent, and the core API is DataSourceProxy.

public class SeataAccountConfig {

    private String applicationName;

    public GlobalTransactionScanner globalTransactionScanner() {
        return new GlobalTransactionScanner(applicationName, "test-tx-group");

    @ConfigurationProperties(prefix = "spring.datasource.druid")
    public DruidDataSource druidDataSource() {
        return new DruidDataSource() ;

    public DataSourceProxy dataSourceProxy(DataSource druidDataSource) {
        return new DataSourceProxy(druidDataSource);

    public SqlSessionFactory sqlSessionFactory(DataSourceProxy dataSourceProxy)throws Exception{
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
        sqlSessionFactoryBean.setTransactionFactory(new SpringManagedTransactionFactory());
        return sqlSessionFactoryBean.getObject();

3. Business code

Core note: Global transactional, which manages the overall distributed transactions.

public class OrderServiceImpl implements OrderService {
    private final Logger LOGGER = LoggerFactory.getLogger(OrderServiceImpl.class);

    private OrderMapper orderMapper ;
    private AccountFeign accountFeign ;
    private InventoryFeign inventoryFeign ;

    public Integer createOrder(String orderNo) {"Order Generating "+orderNo);
        // Order Library of this service
        Integer insertFlag = orderMapper.insert(orderNo) ;
        // Handle account and inventory based on feign interface
        accountFeign.updateAccount(10L) ;
        inventoryFeign.updateInventory(10) ;
        return insertFlag ;

Test process: throw an exception under any service, observe the overall transaction state, and observe whether there is an overall transaction control effect.

5, Source code address

GitHub Address: cicada smiled
GitEE Address: cicada smiled

Recommended reading: Architecture Design Series

Architecture design: single service Cluster Distributed, basic differences and connections
Architecture design: Global ID generation strategy in distributed business system
Architecture design: distributed system scheduling, Zookeeper cluster management
Architecture design: interface idempotency principle, anti duplicate submission Token management
Architecture design: cache management mode, monitoring and memory recycling strategy
Architecture design: asynchronous processing flow, detailed explanation of various implementation modes
Architecture design: peak shaving of high concurrent traffic and locking mechanism of shared resources
Architecture design: distributed service, detailed explanation of library table splitting mode
Architecture design: distributed transaction ① concept introduction and basic theory
Architecture design: Based on the e-commerce transaction process, illustrate the subsection submission of TCC transactions
Architecture design: Based on message oriented middleware, illustrating flexible transaction consistency

Tags: Spring Cloud Microservices seata

Posted by TheAngst on Tue, 17 May 2022 17:14:15 +0300