当前位置:网站首页>What is Seata? In this paper, we understand its implementation principle

What is Seata? In this paper, we understand its implementation principle

2020-12-07 11:24:30 Vivo Internet technology

One 、 background

As the business grows , The single system is gradually unable to meet the needs of the business , Distributed architecture has gradually become the first choice for large-scale Internet platforms . The accompanying problem is , The local transaction scheme can no longer satisfy , Distributed transaction specifications and frameworks emerge as the times require .

under these circumstances , Large vendors implement the distributed transaction specification , Different distributed frameworks are implemented , In order to simplify the business developers to deal with distributed transaction related work , Let developers focus on core business development .

Seata It's such a distributed transaction processing framework ,Seata It's open source by Ali , Formerly known as Fescar, After brand upgrading, it has been transformed into Seata.

Two 、 Distributed transaction specification

1. Distributed transaction related concepts

Business : A program execution unit , Is a user-defined sequence of operations , Need to meet ACID attribute .

Local transactions : Transactions are managed by local resource managers .

Distributed transactions : The operations of the transaction are located at different nodes .

Branch business : In distributed transactions , Local transactions managed by resource managers .

Global transaction : Transactions completed by multiple resource managers at one time , Consists of a set of branching transactions .

2. Distributed transaction implementation specification

For local transactions , Can use DBMS System to achieve transaction management , But for distributed transactions , There's nothing it can do . For distributed transactions , At present, there are mainly 2 Ideas :XA The strong consistency specification of protocol and the final consistency specification of flexible transaction .

2.1 XA

XA Is based on 2 The interface standard of phase submission protocol design , Realized XA Standard resource managers can participate in XA Global transaction . The application assumes the transaction manager TM Work , The database takes on the resource manager RM Work ,TM Generate global transactions id, control RM Commit and roll back of .

2.2 Final consistency of flexible transactions

The specification mainly includes 3 Type of implementation ,TCC、MQ Transaction message 、 Local message table .( There are also other less commonly used implementations such as Saga).

TCC:try/confirm/cancel, stay try Phase locking resources ,confirm Stage to submit , Resource lock failed to execute cancel Stage release resources .

MQ Transaction message : The premise message system needs to support transactions such as RocketMQ, Before the local transaction is executed , Send transaction message prepare, Local transaction executed successfully , Send transaction message commit, Achieve the ultimate consistency of distributed transactions . If the transaction message commit Failure ,RocketMQ The sender will be checked back to ensure that the message is submitted normally , If step 5 Execution failure , retry , Achieve final consistency .

Local message table : Follow MQ Transaction messages are similar to , The difference lies in MQ Transaction messages are not supported , Need to rely on the transaction management capabilities of the local database . Steps in 1 Commit the message to be sent together with the local transaction to DB, With the help of DB To ensure the persistence of messages . step 2 Scan the local message table through , Try sending again , Make sure the message can be sent successfully .

3、 ... and 、Seata framework

1.  System composition

Seata There are three core components :

  • Transaction Coordinator(TC, Transaction coordinator )

    Maintain the state of global and branch transactions , Drive global transaction commit or rollback .

  • Transaction Manager(TM, Transaction manager )

    Define the scope of the global transaction , Start business 、 Commit transaction 、 Roll back the transaction .

  • Resource Manager(RM, Explorer ):

    Managing resources on branch transactions , towards TC Register branch transactions , Reporting branch transaction status , Driving commit or rollback of branch transactions .

The three components work together ,TC With Server Form independent deployment ,TM and RM Integration starts in the application , The overall interaction is as follows :

2. Working mode

Seata Support four working modes :

2.1 AT(Auto Transaction)

AT The pattern is Seata Default working mode . Need to be based on support local ACID Relational database of transactions ,Java application , adopt JDBC Access database .

2.1.1 The whole mechanism

The model is XA The evolution of the agreement ,XA The protocol is based on resource manager implementation , and AT Not so .AT Of 2 The stages are :

  • A stage : Business data and rollback logging are committed in the same local transaction , Release local locks and connection resources .
  • Two stages : Submit asynchronized , Complete... Very quickly ; Rollback is compensated by a phase of rollback log .

The following figure , step 1 Open global transaction ; step 2 Register branch transactions , This corresponds to a stage ; step 3 Commit or roll back branch transactions , It corresponds to two stages .

2.1.2 characteristic
  • advantage : No code intrusion ; High concurrency , The local lock will be released at one stage ; No database pair is required XA Protocol support .
  • shortcoming : It can only be used to support ACID Relational database ;SQL Parsing doesn't support all the syntax yet .

2.2 TCC

The mode is divided into three stages :prepare/commit/cancel.

2.2.1 The whole mechanism
  • TM towards TC Apply for global transaction XID, Propagate to each child call .
  • Where the child calls are TM towards TC Register branch transactions , And execute local prepare, And to TC Report on implementation results .
  • TC According to the execution results of each branch transaction, the second stage is execution commit or rollback.

2.2.2 characteristic
  • advantage : Independent of local affairs .
  • shortcoming : The rollback logic relies on manual encoding ; The business is intrusive .

2.3 Saga Pattern

2.3.1 Saga What is it? ?

1987 Princeton University Hector Garcia-Molina and Kenneth Salem Published an article Paper Sagas, It's about how to deal with long lived transaction( Long life affairs ).Saga It is a long-lived transaction that can be decomposed into a set of sub transactions that can be interleaved . Here's the paper .  

Simply speaking ,Saga Will a long business (T) Break down into a series of Sub Business (Ti), Every Sub Each transaction has a corresponding compensation action (Ci), Used to revoke Ti The impact of transactions .Sub Transactions are committed directly to the library , In the event of an exception , Reverse compensation .

therefore Saga The composition of a business is 2 Kind of :  

  • T1, T2, T3, ..., Tn
  • T1, T2, ..., Tj, Cj,..., C2, C1, among 0 < j < n

The first is the normal submission situation , The second is submitting Tj Transaction exception , The situation in which reverse compensation begins .

Saga The pattern is Seata Long transaction solution provided . For example, external systems are involved in global transactions , Can't manage its resource manager , Let it be transformed into TCC It's not easy to implement , In this case, such a scheme can be adopted .

2.3.2 The whole mechanism

stay Saga In the pattern , Each participant in the business process commits a local transaction , When a participant fails, it compensates the previous successful participant , The first phase forward service and the second phase compensation service are both implemented by business development .

In the figure above, for multiple branch transactions , Omit the repeated occurrence of 2.* step . For business application downtime during global transaction execution , The peer nodes in the business application cluster will use the TC Get related conversations , from DB Load details to restore the state machine .

2.3.3 characteristic
  • advantage : One stage commit local transaction , unlocked , High performance ; Event driven architecture , Participants can execute... Asynchronously , High throughput ; Compensation services are easy to implement .
  • shortcoming : There is no guarantee of isolation .

2.4 XA Pattern

XA It is an interface standard based on the two-stage submission design . For support XA Explorer for , With the help of Seata Framework of the XA Pattern , Can make XA The solution is simpler and easier to use . Use the premise : Need branch database support XA Business , The application for Java application , And the use of JDBC Access database .

2.4.1 The whole mechanism

stay Seata Within the defined distributed transaction framework , Using transactional resources ( database 、 Message service, etc ) Yes XA Protocol support , With XA Protocol mechanism to manage branch transactions Transaction mode .

  • Execution phase : Business sql stay XA To execute in a branch , By branching RM Manager Management , And then execute XA prepare.  
  • Completion stage :TM According to the execution result of each branch, we can pass TC Inform branches to execute XA commit perhaps XA rollback.

2.4.2  characteristic
  • advantage : Inherited XA The advantages of the agreement , Transactions have strong consistency .  
  • shortcoming : Also inherited XA The disadvantages of the agreement , Because branch transactions are open for a long time , Low concurrency .

2.5  Seata Comparison of various modes

There is no silver bullet in the distributed transaction scheme , Choose the right model according to your own business characteristics . For example, the pursuit of strong consistency , You can choose AT and XA, Existence and external system docking , You can choose Saga Pattern , You can't rely on local transactions , May adopt TCC wait . Combine the advantages and disadvantages of each mode to choose .

Four 、AT Pattern core implementation

Whereas Seata There are many supported models , And the default mode is AT, To save space , The following is about AT Pattern analysis and its related core module implementation .

1.  Start of transaction coordinator

TC( Transaction coordinator ) Start as a stand-alone service , As Server, Maintain the state of global and branch transactions , Drive global transaction commit or rollback . Here is TC Startup process :

 

2.  Start of transaction manager

TM( Transaction manager ) Integration starts in the application , Responsible for defining the scope of global transactions , Start business 、 Commit transaction 、 Roll back the transaction .
TM You need to configure GlobalTransactionScannerbean, The following initialization process will be carried out when the application is started :

3 Starting the resource manager

RM( Explorer ) Integration starts in the application , Responsible for managing resources on branch affairs , towards TC Register branch transactions , Reporting branch transaction status , Driving commit or rollback of branch transactions .
RM In addition to the need to follow TM Same configuration GlobalTransactionScanner Start up RMClient, You also need to configure DataSourceProxy, In order to implement the data source access agent . The data source agent implements sql Parsing →  Generate undo-log →  Business sql and undo-log Local submission and other operations .

4. Workflow of global transaction

Here is a simple example to illustrate how global transactions work :

  • BusinessService: Initiate a purchase service
  • StorageService: Inventory management services

The purchase operation is implemented in businessService.purchase in ,purchase Methods are implemented by GlobalTransaction annotation , adopt Dubbo service , Inventory service called deduct Method and method , A sample of :

@GlobalTransactional(timeoutMills = 300000, name = "dubbo-demo-tx")
public void purchase(String userId, String commodityCode, int orderCount) {
    storageService.deduct(commodityCode, orderCount);
    // throw new RuntimeException("xxx");
}

4.1 Successful global transaction flow

4.2 Successful global transaction flow

It's set here BusinessService On successful call StorageService after , Local exception .

5.  Isolated write implementation

Global transaction not committed , When the branch transaction has been committed locally ( Suppose you modify the resource A), How to avoid other transactions from modifying resources at this time A?Seata Using global lock to achieve , The process is as follows :

6.  Read isolation implementation

On the basis of database local isolation level of read committed or above ,Seata Provides read uncommitted , It's easy to understand , Before the global transaction is committed, the branch transaction has been committed locally . If you want to achieve read committed , You need to in select Add... To a sentence for update.

5、 ... and 、 summary

Seata yes Java A powerful distributed transaction framework in the field , It supports a variety of patterns . The default support is AT Pattern , Compared to traditional 2PC agreement ( database-based XA agreement ), Well solved 2PC The problem of locking resources for a long time , Increased concurrency .Seata Among the various modes supported ,AT Pattern zero intrusion to business to realize distributed transaction , More developer friendly . in addition Seata Of Server Cluster mode can be used when selecting the appropriate storage medium , Reduce the impact of a single point of failure .

This article mainly refers to the official website and some blogs , At the same time I read AT Pattern implementation source code , If there's something wrong , Hope to point out , Discuss and communicate with each other .

6、 ... and 、 Reference resources

author :vivo Official website mall development team

版权声明
本文为[Vivo Internet technology]所创,转载请带上原文链接,感谢
https://chowdera.com/2020/12/20201207112252597f.html