An overview,

Under the microservice architecture, although we will try to avoid distributed transactions, as long as the business is complex, this is an unavoidable problem, how to ensure the consistency of business data? This article mainly introduces the use of Seata’s AT mode to solve the consistency problem in synchronous scenarios.

Seata is alibaba’s open source middleware of one-stop distributed transaction solution, which solves distributed transaction problems in microservice scenarios in an efficient and zero-intrusion way

 

Introduction to Seata

The overall transaction logic is based on a two-phase commit model with three core concepts:

  • TM: Originator of a transaction. Used to tell THE TC the start, commit, rollback of a global transaction.
  • RM: Specifies transaction resources. Each RM is registered with the TC as a branch transaction.
  • TC: Transaction coordinator seata-Server, used to receive registration, commit and rollback of our transactions.

Seata currently has two modes available for different business scenarios

2.1. The AT mode

Scenarios suitable for this mode:

  • Based on support localACIDA relational database for transactions.
  • Java application, passJDBCAccess the database.

A typical distributed transaction process:

  1. TMTCRequest to start a global transaction. The global transaction was successfully created and a globally unique transaction was generatedXID.
  2. XIDPropagated in the context of the microservice invocation link.
  3. RMTCRegister branch transactions and bring them under the jurisdiction of the global transaction corresponding to the XID.
  4. TMTCagainstXIDGlobal commit or rollback resolution.
  5. TCschedulingXIDAll branch transactions under jurisdiction complete commit or rollback requests.

 

2.2 MT

This mode is similar to TCC. You need to customize the prepare, COMMIT, and ROLLBACK logic. It is suitable for non-relational database scenarios

 

3. Sample Seata scenario

Simulate a simple user Order scenario, four sub-projects are Bussiness(transaction initiator), Order(create Order), Storage(deduct inventory) and Account(deduct Account balance)

3.1. Deploy the Server of Seata

Discover registration, Config configuration and Store storage modules all use file by default, which can only be used on a single machine. When we installed them, we changed to use nacOS and Mysql respectively to support server cluster

3.1.1. Download the latest version and unpack it

Github.com/seata/seata…

 

3.1.2. Modify the conf/registry

Registries and configuration centers are file by default; nacOS instead; Set type in the Registry and Config nodes to nacOS and change serverAddr to your NACOS node address.

Registry {type = "nacos" nacos {serverAddr = "192.168.28.130" Namespace = "public" cluster = "default"}} config { Type = "nacos" {serverAddr = "192.168.28.130" namespace = "public" cluster = "default"}}Copy the code

 

3.1.3. Modify the conf/nacos-config. TXT configuration

  • Change service.vgroup_mapping to the name of the application. If there are multiple services, add corresponding configurations

Default group called ${spring. Application. The name} – fescar – service – group, by spring. Cloud. Alibaba. Seata. Tx – service – group configuration changes

  • Modify thestore.modedbAnd modify database configurations

 

3.1.4. Initialize the NACOS configuration of SEATA

cdThe conf sh nacos - config. Sh 192.168.28.130Copy the code

You can see the seATA configuration in the configuration list of NACOS

 

3.1.5. Initialize database

Execute the script in conf/db_store.sql

 

3.1.6. Start seata – server

Sh -p 8091 -h 192.168.28.130Copy the code

 

3.2. Application Configuration

3.2.1. Initialize the database

Execute the script seata-demo.sql

You need to add the undo_log table to service-related databases to save the data to be rolled back

 

3.2.2. Add registry. Conf configuration

Just copy registry. Conf from Seata-server to each service without modification

 

3.2.3. Modify the configuration

Each service in demo modifies the configuration file individually

  • Bootstrap. yml Modifies the NACOS address
  • Application. yml Modifies the database configuration

 

3.2.4. Configure the data source agent

Seata is through the data source to realize distributed transactions, so need to configure the IO. Seata. Rm. The datasource. DataSourceProxy Bean, and is the default @ Primary data source, otherwise the transaction will not rolled back, unable to realize the distributed transaction

public class DataSourceProxyConfig {
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DruidDataSource druidDataSource(a) {
        return new DruidDataSource();
    }

    @Primary
    @Bean
    public DataSourceProxy dataSourceProxy(DruidDataSource druidDataSource) {
        return newDataSourceProxy(druidDataSource); }}Copy the code

Because of using the mybatis starter so need to eliminate DataSourceAutoConfiguration, or it will produce circular dependencies

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
Copy the code

 

3.2.5. The transaction initiator adds global transaction annotations

The transaction initiator business-Service adds the @GlobalTransactional annotation

@GlobalTransactional
public void placeOrder(String userId) {... }Copy the code

 

3.3. Test

Two interface tests are provided

  1. Transaction success: excluding inventory deduct a successful order > create > http://localhost:9090/placeOrder account balance success
  2. Transaction failure: excluding inventory successful order > create > deductions account balance failure, transaction rollback http://localhost:9090/placeOrderFallBack

 

3.4. Demo download address

Gitee.com/zlt2000/mic…

 

Recommended reading

  • Log troubleshooting difficulty? Distributed log link tracing to help you
  • Zuul integrates Sentinel’s latest gateway flow control components
  • Ali Registry Nacos production deployment solution
  • Spring Boot custom configuration items implement automatic prompts in the IDE
  • How to do Spring Cloud Zuul dynamic routing? Integrating the Nacos implementation is simple
  • How can Spring Cloud developers resolve service conflicts and instance hopping?

Scan code attention has surprise!