Distributed transaction solution based on Seata
preface
The last article has taken you to understand the basic solution of distributed transaction, today I will introduce you to the distributed transaction middleware Seata, and write a demo based on Seata distributed transaction
The body of the
background
In January 2019, Alibaba middleware team launched the open source project Fescar (Fast & EaSy Commit And Rollback) to jointly build the open source distributed transaction solution with the community. Fescar’s vision is to make the use of distributed transactions as simple and efficient as the use of local transactions, and to gradually solve all the problems that developers encounter with distributed transactions. After Fescar was open source, Ant Financial joined the Fescar community and contributed TCC mode in Fescar 0.4.0. In order to create a more neutral, open and ecological distributed transaction open source community, after the vote of the core members of the community, we decided to upgrade the brand of Fescar and renamed it Seata, which means: Simple Extensible Autonomous Transaction Architecture is a one-stop distributed Transaction solution.
What is Seata?
Seata is an open source distributed solution dedicated to providing high performance and easy to use distributed transaction services. It was designed to:
- Non-intrusive to the business: Intrusive here means that applications need to be designed and adapted at the business level because of the technical constraints of distributed transactions. This kind of design and modification often brings high development and maintenance costs to the application. Solving the distributed transaction problem at the middleware level does not require additional work at the business level.
- High performance: The introduction of distributed transaction guarantees inevitably leads to additional overhead and performance degradation. The performance loss of the introduction of distributed transactions is reduced to a very low level, so that the application will not be affected by the introduction of distributed transactions resulting in the availability of business
Seata provides users with AT mode, TCC mode, Soga mode and XA transaction mode to create a one-stop distributed transaction solution for users.
Let’s take a look at the important components of Seata:
- Transcation Coordinator(TC) : Transaction Coordinator that maintains the transaction state of global transactions and coordinates and drives the submission or rollback of global transactions
- Transaction Manager(TM): Maintains the boundaries of a global Transaction, is responsible for initiating a global Transaction, and is responsible for initiating the commit or rollback resolution of the global Transaction
- Resource Manger(RM): Control branch transactions, register branch transactions, report the status of branch transactions, receive instructions from the transaction coordinator, drive the commit or rollback of local transactions, namely, seata-client, the transaction participant, is responsible for the local transaction processing and interaction with Seata-server
A typical distributed transaction process:
- TM initiates a global transaction to TC, and TC successfully creates a global transaction and generates a globally unique XID
- The XID is passed in the entire service invocation context
- RM registers branch transactions with the TC and merges them into the global transaction of the corresponding XID
- TM initiates a commit or rollback resolution for the XID global transaction to TC
- TC schedules all branch transactions under XID to complete commit or rollback requests.
Let’s look at the various Seata transaction modes
AT mode
The USE of the AT pattern is advanced: first, based on a relational database that supports ACID, but Java applications, through JDBC access to the database. The AT pattern is an improvement on the XA-BASED solution by taking the resource manager out of the database layer and deploying it as a two-sided middleware layer on the application side. Does not depend on the database’s own support for the protocol, and certainly does not require the database to support XA.
Its basic steps:
- A phase:
- Parsing business SQL
- Get the mirror before SQL execution
- Execute business SQL
- Get the mirror after SQL execution, after the mirror
- Add the undo_log to the undo_log table. The rollback logs are composed of the image data and service SQL information
- Register branch transactions with the TC and apply for global locks
- Transaction commit, which commits business operations along with undo_log
- Release local locks and database connection resources
- Stage 2 – Submission:
- After receiving a request from the TC to commit a branch transaction, it puts the request into an asynchronous task queue and returns success to the TC immediately
- A branch submit request in the asynchronous task phase deletes the corresponding UNDO LOG records asynchronously and in batches
- Phase 2 – Rollback:
- Received a rollback request from the TC, and started a transaction
- Search for UNDO_LOG records based on the XID and Branch ID
- Data verification: Compare the mirror in UNDO LOG with the current data. If there is a difference, the data has been modified by an action other than the current global transaction. In this case, you need to handle it according to the configuration policy
- Generate and execute rollback statements based on the former image and business SQL information in UNDO LOG
- Commit local Transaction
At this point, some students may ask why it can release the lock in the first stage
The JDBC data source agent of Seata parses business SQL, organizes the data mirror of business data before and after the update into rollback log, and commits the update of business data and the write of rollback log in the same local transaction by taking advantage of the ACID property of local transaction. This ensures that any updates to committed business data are accompanied by a rollback log. Based on this design, the local lock can be released in the first phase
So how does the AT pattern guarantee write isolation
- Local transactions apply for a global lock before committing. Ensure that the global lock is obtained before committing
- The commit will not occur unless a global lock is obtained
- Applying for a global lock has a limit beyond which the local transaction is rolled back and the local lock is released
How to ensure read isolation
The default global isolation level for Seata’s AT mode is read uncommitted. If the application is applied in certain scenarios, it must require that the global read has been committed. Currently, Seata is brokered through SELECT FOR UPDATE statements. The execution of the SELECT FOR UPDATE statement requests a global lock, and if the global lock is held by another transaction, the local lock is released (roll back the local execution of the SELECT FOR UPDATE statement) and retry. In this process, the query is held by the block and is not returned until the global lock is taken, i.e. the relevant data read is committed. FOR overall performance, Seata’s current approach does not proxy all SELECT statements, only SELECT statements FOR UPDATE.
Advantages and disadvantages of AT mode
Advantages:
- Database support for the XA protocol is not required
- Concurrency and throughput increase, and local locks can be released in the first phase
disadvantages
- This can only be used in relational databases that support ACID
- Transaction isolation levels are supported up to read committed levels, SQL parsing does not cover the full syntax, etc.
TCC mode
The TCC pattern can incorporate custom branch transactions into global transactions, independent of the dependency of the underlying data resources on the transaction
Its processing is as follows:
- One-stage Prepare behavior: The customized prepare logic is invoked.
- Two-stage COMMIT behavior: Custom commit logic is invoked.
- Two-stage ROLLBACK behavior: Invoke custom ROLLBACK logic.
@LocalTCC
public interface TccAcountAction {
@TwoPhaseBusinessAction(name = "DubboTccActionTwo" , commitMethod = "commit", rollbackMethod = "rollback")
public boolean prepare(BusinessActionContext actionContext,
@BusinessActionContextParameter(paramName = "b") String b,
@BusinessActionContextParameter(paramName = "c", index = 0) List list);
public boolean commit(BusinessActionContext actionContext);
public boolean rollback(BusinessActionContext actionContext);
}
Copy the code
The whole transaction process:
- TM initiates a global transaction to TC, and TC successfully creates a global transaction and generates a globally unique XID
- Branch transactions are executed in turn
- – Register branch transactions with TCS
- The prepare method is called to execute the prepare phase of the transaction
- Commit or rollback the global transaction. The TC issues a commit or rollbac to each RM, which calls the written commit or rollback methods
Advantages and disadvantages of TCC mode
Advantages:
- Many non-transactional resources, such as caches, can be incorporated into the management of global transactions
Disadvantages:
- Implement the compensation logic yourself
Soga model
Saga mode is a long transaction solution provided by SEATA. In Saga mode, each participant in the business process submits a local transaction, and when a participant fails, the previous successful participant is compensated. One-stage forward service and two-stage compensation service are implemented by business development.
Implementation of Saga:
Currently, the Saga mode provided by SEATA is implemented based on the state machine engine. The mechanism is as follows:
- Define the flow of the service invocation through a state diagram and generate a JSON state language definition file
- A node in a state diagram can invoke a service, and a node can configure its compensation node
- The state graph JSON is executed by the state machine engine. When an exception occurs, the state engine reverse-executes the successful node and the corresponding compensation node rolls back the transaction
Note: Whether to compensate when an exception occurs is also user-definable
- It can realize service choreography requirements, supporting single choice, concurrency, sub-process, parameter conversion, parameter mapping, service execution state judgment, exception capture and other functions
Applicable scenarios:
- Long business process, many business process
- Participants include other corporate or legacy system services that do not provide the three interfaces required by the TCC pattern
Advantage:
- One-stage commit local transaction, no lock, high performance
- Event-driven architecture, asynchronous execution of participants, high throughput
- Compensation services are easy to implement
Disadvantages:
- Isolation is not guaranteed
Small make up himself wrote a Seata based AT the demo mode/TCC, making address: https://github.com/GBBP1813/seata-use
Distributed solution based on distributed transaction middleware SEATA
This Demo project realizes AT/MT mode based on SEATA/SEATa-SAMPLE
Technology Stack involved:
springboot dubbo zookeeper
Use the demo steps in this case
1. Prepare projects
Clone the project to the local computer, import idea, JDK for 1.8 Create service database SQL include undo table in the project
Module:
Seata- Order service module
Seata- Storage inventory service module
Seata-account account service module
Seata-common public module
Seata transcation – manage TM module
2. Prepare the environment
1) download seata – first server address: https://github.com/seata/seata/releases after downloading the database configuration
The demo uses DB mode to store transaction logs. Create three tables: global_table, branch_table, and lock_table. SQL Create tables in the /conf/db_store. SQL file of seata-server. The configuration file transaction group can also be modified by itself, and changes in the project should be made accordingly
2) Start the local ZooKeeper
3) Start seata-server
3. Start the project
Start the four sub-modules of the project respectively
4. Mock requests
AT mode
Commit:
curl -H "Content-Type:application/json" -X POST -d '{" userId ", "1", "commodityCode" : "C201901140001", "name" : "computer," "count" : 1, "the amount" : "10"}' 'localhost:8004/tmManager/buy'
Copy the code
The Rollback:
curl -H "Content-Type:application/json" -X POST -d '{" userId ", "1", "commodityCode" : "C201901140001", "name" : "computer," "count" : 1, "the amount" : "10"}' 'localhost:8004/tmManager/buy? throwExp=true'
Copy the code
TCC mode:
Commit:
curl -H "Content-Type:application/json" -X POST -d ' ' 'localhost:8004/tcc/bug'
Copy the code
Rollback:
curl -H "Content-Type:application/json" -X POST -d ' ' 'localhost:8004/tcc/bug? throwExp=true'
Copy the code
IO/zh-CN /docs/…