springcloudAlibaba---Distributed transaction component Seata

Introduction

A transaction is a program execution unit that accesses and possibly updates various data items in the database. In a relational database
, a transaction consists of a set of SQL statements. Transactions should have four attributes: atomicity, consistency, isolation, and durability.
These four properties are often called ACID properties.
Atomicity: A transaction is an indivisible unit of work, and all operations included in the transaction are either done or none
.
Consistency: A transaction must change the database from one consistency state to another, and
the intermediate state of the transaction cannot be observed.
Isolation: The execution of a transaction cannot be interfered with by other transactions. That is, the operations and data used within a transaction
are isolated from other concurrent transactions, and concurrently executed transactions cannot interfere with each other. Isolation is divided into four levels: read
uncommitted, read committed (to solve dirty reads), repeatable read (repeatable
read, to solve phantom reads), serializable (to solve phantom reads) ).
Durability: Durability, also called permanence, means that once a transaction is committed, its
changes to the data in the database should be permanent. Subsequent operations or failures should not have any impact on it.
When implementing any transaction mechanism, the ACID characteristics of transactions should be considered, including: local transactions and distributed transactions. If they cannot be
fully satisfied in time, the extent to which they can be supported must also be considered.

Local Transaction
@Transational
In most scenarios, our application only needs to operate a single database. The transaction in this case is called a local transaction
(Local Transaction). The ACID properties of local transactions are directly supported by the database. The local transaction application architecture is as follows
:
In JDBC programming, we use the java.sql.Connection object to open, close or submit transactions. The code looks like this
:

1 Connection conn = ... //获取数据库连接
2 conn.setAutoCommit(false); //开启事务
3 try{
    
    
4    //...执行增删改查sql
5    conn.commit(); //提交事务
6 }catch (Exception e) {
    
    
7   conn.rollback();//事务回滚
8 }finally{
    
    
9    conn.close();//关闭链接
10 }

Typical scenarios of distributed transactions

At present, the development of the Internet is in full swing, and most companies have carried out database splitting and service-oriented (SOA). In this case, completing a certain business function may require operating across multiple services and multiple databases. This involves distributed transactions, where the resources that need to be operated are located on multiple resource servers, and the application needs to ensure that all operations on data from multiple resource servers either succeed or fail. Essentially, distributed transactions are to ensure data consistency among different resource servers.
Typical distributed transaction scenario:
cross-database transaction
Cross-database transaction means that a certain function of an application needs to operate multiple libraries, and different business data are stored in different libraries. The author has seen
a relatively complex business in which 9 libraries were operated at the same time.
Insert image description here
Splitting databases and tables
Usually when a database has a large data volume or the expected future data volume is relatively large, it will be split horizontally, that is, into databases and tables. As shown
in the figure below, database B is split into 2 libraries:

For the case of sub-database and sub-table, developers generally use some database middleware to reduce the complexity of SQL operations. For example, for
sql: insert into user(id,name) values ​​(1, "Zhang San"), (2, "Li Si"). This SQL is the syntax for operating a single database.
In the case of a single database, transaction consistency can be guaranteed.
However, since the database and tables are now divided into sub-databases, the developer hopes to insert record No. 1 into sub-database 1 and record No. 2 into sub-database 2. Therefore, the
database middleware needs to rewrite it into two SQL statements and insert them into two different sub-databases respectively. At this time, it is necessary to ensure that both libraries succeed or
fail. Therefore, basically all database middleware Facing the problem of distributed transactions.
Insert image description here

Service-oriented
microservice architecture is a relatively popular concept at present. For example, in the case mentioned by the author above, an application operates
9 libraries at the same time. The business logic of such an application must be very complex, which is a great challenge for developers. It should be split into different independent
services to simplify the business logic. . After splitting, independent services can make remote calls through the RPC framework to communicate with each other. The figure below
demonstrates an architecture in which three services call each other:
Service A needs to directly operate the database to complete a certain function, and needs to call Service B and Service C at the same time. Service B
operates two databases at the same time, and Service C also operates a library. It is necessary to ensure that these cross-service operations on multiple databases either
succeed or fail. In fact, this may be the most typical distributed transaction scenario.

小结:上述讨论的分布式事务场景中,无一例外的都直接或者间接的操作了多个数据库。如何保证事务的ACID特性,对于分布式事务实现方案而言,是非常大的挑战。同时,分布式事务实现方案还必须要考虑性能的问题,如果为了严格保证ACID特性,导致性能严重下降,那么对于一些要求快速响应的业务,是无法接受的。

Insert image description here
Common distributed transaction solutions
1, seata Alibaba distributed transaction framework
2, message queue
3, saga
4, XA

Theoretical basis of distributed things

Currently, the mainstream distributed transaction solutions on the market are all 2PC protocols. This is the internal reason why among the common distributed transaction solutions mentioned at the beginning of the article, those listed all have one thing in common: "two stages". When some articles analyze 2PC, they almost always use the example of two phases of TCC, the first phase is try, and the second phase is to complete confirm or cancel. In fact, 2PC is not specifically designed to implement TCC. 2PC is universal and exists as a protocol. Most of the current distributed solutions are based on the two-phase submission protocol 2PC. TCC (Try-Confirm-Cancel) is actually a service-based two-stage submission protocol.

2PC two-phase commit protocol, divided into Prepare and Commit
prepare: things submit transaction requests
Insert image description here

  1. Ask the coordinator to send a transaction request to all participants, ask whether the transaction operation can be performed, and then wait for the response of each participant.
  2. After each participant receives the coordinator's transaction request, it performs transaction operations (such as updating records in a relational database table) and
    records Undo and Redo information in the transaction log.
  3. Response If the participant successfully executes the transaction and writes Undo and Redo information, a YES response is returned to the coordinator, otherwise a NO
    response is returned. Of course, the participant may also be down and no response will be returned

Commit: Execute transaction submission.
Executing transaction submission is divided into two situations, normal submission and rollback.
Insert image description here

  1. The commit request coordinator sends a Commit request to all participants.
  2. After the transaction submission participant receives the Commit request, it executes the transaction submission and releases all resources occupied during the transaction execution period after the submission is completed.
  3. After the feedback result participant executes the transaction submission, it sends an Ack response to the coordinator.
  4. Completion Transaction After receiving Ack responses from all participants, the transaction is completed and committed.

Interrupting the transaction
During the execution of the Prepare step, if some participants fail to execute the transaction, are down, or the network with the coordinator is interrupted, then the coordinator cannot
receive YES responses from all participants, or a participant returns If a No response is received, the coordinator will enter the rollback process and roll back the transaction
. The process is as shown in the red part of the figure below (replace the Commit request with the red Rollback request):
Insert image description here

  1. rollback request The coordinator sends a Rollback request to all participants.

  2. After the transaction rollback participant receives the Rollback, it uses the Undo log in the Prepare phase to perform the transaction rollback, and releases all resources occupied during the transaction execution period after completion .
  3. The feedback result participant sends an Ack response to the coordinator after performing transaction rollback.
  4. After the interrupt transaction receives Ack responses from all participants, the transaction interrupt is completed.

2PC problem

  1. When synchronous blocking participants are waiting for instructions from the coordinator, they are actually waiting for responses from other participants. During this process, participants are unable to perform
    other operations, that is, their operation is blocked. If there is an abnormality in the network between the participant and the coordinator that prevents the participant from receiving information from the coordinator
    , it will cause the participant to remain blocked.
  2. In single point 2PC, all requests come from the coordinator, so the status of the coordinator is crucial. If the coordinator goes down, the
    participants will be blocked and occupy transaction resources.
    If the coordinator is also distributed and uses the master selection method to provide services, then after one coordinator hangs up, another coordinator can be selected to continue subsequent services
    , which can solve the single point problem. However, the new coordinator cannot know all the status information of the previous transaction (such as the length of time it has waited for the Prepare response, etc.
    ), so it cannot handle the previous transaction smoothly.
  3. Inconsistent data. During the Commit transaction, the Commit request/Rollback request may be lost due to the coordinator downtime or
    network . This results in some participants not receiving the Commit/Rollback request, while other participants receive it normally. Until the Commit/Rollback operation is performed
    , participants who have not received the request will continue to block. At this point, the data are no longer consistent across participants.
    When the participant executes Commit/Rollback, it will send an Ack to the coordinator. However, regardless of whether the coordinator receives the Ack from all participants,
    there will be no other remedies for the transaction. All the coordinator can do is wait for the timeout. Then the transaction initiator returns "I'm not sure whether the transaction was successful
    ."
  4. The reliability of the environment depends on the coordinator. After the Prepare request is issued, it waits for a response. However, if a participant goes down or the network with the coordinator is
    interrupted, the coordinator will not be able to receive responses from all participants. Then in 2PC, coordination The coordinator will wait for a certain period of time, and then after timeout,
    a transaction interruption will be triggered. During this process, the coordinator and all other participants are blocked.
    This mechanism is too harsh for real-world environments where network problems are common .

AT mode (auto transcation) distributed transaction implementation

AT mode is a non-intrusive distributed transaction solution.
Alibaba seata framework implements this pattern.
In AT mode, users only need to pay attention to their own "business SQL". As the first stage of the user's "business SQL", the Seata framework will automatically generate the two-stage commit and rollback operations of the transaction.
Insert image description here
How AT mode achieves no intrusion into the business:
Phase One:
In the first phase, Seata will intercept the "Business SQL", first parse the SQL semantics, and find the business
data . Before the business data is updated, Save it as "before image", then execute "Business SQL" to update the business data.
After the business data is updated, save it as "after image", and finally generate a row lock. All the above operations
are completed within a database transaction, thus ensuring the atomicity of one-stage operations.
If the second stage is submitted, because the "business SQL" has been submitted to the database in the first stage, the Seata framework only needs to
delete the snapshot data and row locks saved in the first stage to complete data cleaning.
Insert image description here
Insert image description here
Insert image description here
If the second stage is a rollback, Seata needs to roll back the "business SQL" that has been executed in the first stage and restore the business data. The rollback method is to use "before image" to restore business data; but before restoring, dirty writes must first be verified. Compare "database current business data" and "after image". If the two data are completely consistent, it means there are no dirty writes. , business data can be restored. If it is inconsistent, it means there is dirty writing. If dirty writing occurs, manual processing is required. The
first-stage, second-stage commit and rollback of AT mode are automatically generated by the Seata framework. Users only need to write "business SQL". You can
easily access distributed transactions. AT mode is a distributed transaction solution without any intrusion into the business.

TCC mode

  1. It is relatively intrusive, and you have to implement the relevant transaction control logic yourself.
    2. There are basically no locks in the whole process, and the performance is stronger.
    The TCC mode requires users to implement the three operations of Try, Confirm and Cancel according to their own business scenarios; the transaction initiator is in the first stage
    In the segment execution Try mode, the Confirm method is executed during the second-phase submission, and the Cancel method is executed during the second-phase rollback.
    Insert image description here

Description of the three methods of TCC:
Try: detection and reservation of resources;
Confirm: submission of the executed business operation; if Try is successful, Confirm must be successful;
Cancel: release of reserved resources;
TCC practical experience
Ant Financial TCC practice, summary The following considerations:
➢Business model is designed in 2 stages
➢Concurrency control
➢Allow empty rollback
➢Anti-hanging control
➢Impotent control
1 TCC design – The business model is designed in 2 stages:
users access TCC, the most important thing is to consider how to Our business model is divided into two stages to implement.
Take the "deduct money" scenario as an example. Before connecting to TCC, the deduction of money from account A can be
completed . However, after connecting to TCC, the user needs to consider how to change the original one-step process. The debit operation that can be completed is divided into two stages and implemented
into three methods, and it is guaranteed that if the first stage Try is successful, the second stage Confirm will be successful.
Insert image description here

As shown in the figure above, the Try method is a one-stage preparation method and requires resource checking and reservation. In the money deduction scenario,
what Try has to do is to check whether the account balance is sufficient and reserve transfer funds. The way to reserve is to freeze the transfer funds in Account A. After the Try
method is executed, although the balance of account A is still 100, 30 yuan of it has been frozen and cannot be used for other transactions.
The second-stage Confirm method performs the actual deduction operation. Confirm will use the funds frozen in the Try stage to perform account deductions.
After the Confirm method is executed, the 30 yuan frozen in the first stage of account A has been deducted, and the balance of account A becomes 70 yuan.
If the second stage is a rollback, you need to release the 30 yuan frozen in the first stage Try in the Cancel method so that account A returns to the initial
state and all 100 yuan is available.
When users access the TCC model, the most important thing is to consider how to split the business model into two phases, implement the three TCC methods
, and ensure that Try and Confirm will succeed. Compared with AT mode, TCC mode is somewhat intrusive to business code
, but TCC mode does not have the global row lock of AT mode, and TCC performance will be much higher than AT mode.

2.TCC design-allowing empty rollback.
Insert image description here
The Cancel interface design needs to allow empty rollback. If the Try interface is not received due to packet loss, the transaction manager will trigger a rollback, and
the Cancel interface will be triggered. At this time, when Cancel is executed and finds that there is no corresponding transaction xid or primary key, it needs to return a rollback
success. Let the transaction service manager think that it has been rolled back, otherwise it will keep retrying, and Cancel has no corresponding business data to roll back
.
3.TCC design - anti-hanging control
Insert image description here
Hanging means: Cancel is executed before the Try interface. The reason is that Try times out due to network congestion, the transaction manager
generates a rollback, triggers the Cancel interface, and finally receives the Try interface. Called, but Cancel arrives before Try. According to the previous
logic of allowing empty rollback, the rollback will return successfully. The transaction manager believes that the transaction has been rolled back successfully, so the Try interface should not be
executed , otherwise data inconsistency will occur, so we cancel the empty rollback Before returning successfully, record the transaction xid or business primary
key to indicate that this record has been rolled back. The Try interface first checks the transaction xid or business primary key. If it has been marked as rolled back successfully, the
Try business operation will not be executed. .
4.TCC design - idempotent control
Insert image description here
Idempotence means: for the same system, using the same conditions, one request and repeated multiple requests have the
same impact on system resources. Because network jitter or congestion may time out, the transaction manager will retry the resource operation, so it is likely that a business
operation will be called repeatedly. In order not to occupy resources multiple times due to repeated calls, the service design needs to be idempotent. Control, usually we
can use transaction xid or business primary key judgment to control.

Saga mode

The implementation of saga mode is a long transaction solution.
Saga is a compensation protocol. In Saga mode, there are multiple participants in a distributed transaction. Each participant is a reversal
compensation service, which requires users to implement forward operations and reverse rollback operations according to business scenarios.
Insert image description here

As shown in the figure: T1 T3 are all forward business processes, and they all correspond to a forward and reverse operation C1 C3
. During the execution of a distributed transaction, the forward operations of each participant are executed in sequence. If all forward operations are executed successfully, then the distribution transaction
commit. If any forward operation fails, the distributed transaction will go back to perform the reverse rollback
operation of the previous participants, roll back the submitted participants, and return the distributed transaction to the initial state.
Saga forward services and compensation services also need to be implemented by business developers. Therefore, it is business intrusion.
Distributed transactions in Saga mode are usually event-driven, and each participant is executed asynchronously. Saga mode is a long transaction
solution.

Saga mode usage scenarios
Saga mode is suitable for business systems with long business processes and the need to ensure the final consistency of transactions. Saga mode will submit local
transactions in one stage, and can guarantee performance in the case of lock-free and long processes.
The transaction participants may be services of other companies or services of legacy systems that cannot be transformed and provide the interfaces required by TCC, so the
Saga mode can be used.
The advantages of the Saga model are:
one-stage submission of local database transactions, lock-free, high performance;
participants can use transaction-driven asynchronous execution, high throughput;
the compensation service is the "reverse" of the forward service, easy to understand and implement;
Disadvantages : Saga mode cannot guarantee
isolation because the local database transaction has been submitted in the first stage and no "reservation" action has been performed . Responses to the lack of isolation will be discussed later.
The same as the practical experience of TCC is that in the Saga mode, the reverse and reverse operations of each transaction participant need to support:
empty compensation: the reverse operation is earlier than the forward operation;
anti-hanging control: the forward operation must be rejected after empty compensation Operation
idempotent

XA mode

XA mode
XA is a two-phase commit protocol defined by the X/Open DTP group
. support.
The X/Open DTP model (1994) includes application program (AP), transaction manager (TM), and resource manager (RM).
XA interface functions are provided by database vendors. The foundation of the XA specification is the two-phase commit protocol 2PC.
JTA (Java Transaction API) is an enhanced interface of the XA specification implemented in Java.
In XA mode, a [global] coordinator is required. After each database transaction is completed, the first phase of pre-commit is performed, the coordinator is notified
, and the results are given to the coordinator. After the coordinator completes all branch transaction operations and pre-commits them, proceed to the second step; the second step: the coordinator
notifies each database to commit/rollback one by one.
Among them, the global coordinator is the TM role in the XA model, and the database of each branch transaction is the RM.
XA implementation provided by MySQL (https://dev.mysql.com/doc/refman/5.7/en/xa.html)
The open source framework in XA mode is atomikos, and its development company also has a commercial version.
Disadvantages of XA mode: large transaction granularity. Under high concurrency, system availability is low. Therefore it is rarely used.

( AT
, TCC, Saga,
In scenarios where you want to transform your business, the
learning cost is almost zero.
TCC mode is a high-performance distributed transaction solution, suitable for scenarios with high performance requirements such as core systems.
Saga mode is a long transaction solution, suitable for business systems with long business processes and the need to ensure the final consistency of transactions.
Saga mode will submit local transactions in one stage, without locks, and can guarantee performance in long process situations. It is mostly used at the channel layer, Integrated
layer business system. The transaction participants may be services of other companies or services of legacy systems that cannot be transformed and provide
the interfaces required by TCC. Saga mode can also be used.
XA mode is a solution for distributed strong consistency, but its performance is low and it is rarely used.

Use of Seata distributed transactions

Seata is an open source distributed transaction solution dedicated 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. AT mode is the first mode recommended by Alibaba. There is a commercial version of GTS (Global Transaction Service) on Alibaba Cloud.

Seata's three major roles
In Seata's architecture, there are three roles: TC (Transaction Coordinator) - the transaction coordinator maintains the status of global and branch transactions and drives global transaction submission or rollback. TM (Transaction Manager) - The transaction manager defines the scope of a global transaction: starts a global transaction, commits or rolls back a global transaction.
RM (Resource Manager) - The resource manager manages resources for branch transaction processing, talks to the TC to register branch transactions and report the status of branch transactions, and drives branch transactions to commit or rollback. Among them, TC is a separately deployed Server, and TM and RM are Clients embedded in the application.

Distributed transaction life cycle

In Seata, the life cycle of a distributed transaction is as follows:
Insert image description here
1. TM requests TC to start a global transaction. TC will generate an XID as the number of the global transaction. XID will be propagated in the calling link of microservices to ensure that
sub-transactions of multiple microservices are associated together.
When entering the transaction method, an XID will be generated, and global_table is the stored global transaction information.
2.RM requests TC to register the local transaction as a branch transaction of the global transaction, and associate it through the XID of the global transaction.
When running the database operation method, branch_table storage transaction participant
3.TM requests TC to tell the XID whether the corresponding global transaction is committed or rolled back.
4. TC drives RMs to commit or roll back their own local transactions corresponding to the XID.

The core of the AT mode is non-intrusion into the business. It is an improved two-stage submission. Its design idea is as shown in the figure. In the
first stage,
business data and rollback log records are submitted in the same local transaction, and local locks and connection resources are released. The core is to parse the business SQL, convert it into undolog, and
store it in the database at the same time. How is this done? First, let’s throw out the concept of DataSourceProxy proxy data source. You can probably basically guess what the operation is by the name. We will do a detailed analysis later. In the
second stage
, if the distributed transaction operation is successful, TC will notify RM to asynchronously delete the undolog.
The distributed transaction operation failed. TM sends a rollback request to TC, and RM receives the rollback request from the coordinator TC, finds the corresponding rollback log record through XID and Branch ID, and generates the reverse update SQL through the rollback record and executes it to complete the branch. of rollback.

Compared with other distributed transaction frameworks, the highlights of the Seata architecture include:

  1. The application layer implements automatic compensation based on SQL parsing, thereby minimizing business intrusion;
  2. Deploy TC (transaction coordinator) independently in distributed transactions and be responsible for transaction registration and rollback;
  3. Implemented write isolation and read isolation through global locks

Performance loss
An Update SQL requires global transaction xid acquisition (communication with TC), before image (parsing the SQL, querying the database once), after image (querying the database once), insert undo log (writing to the database once), before commit ( Communicate with TC, determine lock conflicts), these operations require a remote communication RPC, and are synchronous. In addition, the insertion performance of blob fields when writing undo log is also not high. Each SQL statement will add so much overhead, and it is roughly estimated that the response time will increase by 5 times. Cost-Effectiveness
In order to perform automatic compensation, it is necessary to generate and persist front and rear mirrors for all transactions. However, in actual business scenarios, how high is the success rate, or what proportion of distributed transactions need to be rolled back if they fail? According to the 80/20 rule, in order to roll back 20% of transactions, the response time of 80% of successful transactions needs to be increased by 5 times. Is this cost worth it compared to asking the application to develop a compensation transaction?
Global lock hotspot data Compared with XA, Seata will release the database lock after the first stage is successful, but the determination of the global lock before commit in the first stage also lengthens the holding time of the data lock. This overhead is much lower than XA's prepare. Conduct testing based on actual business scenarios. The introduction of global locks achieves isolation, but the problem it brings is blocking and reduced concurrency, especially for hot data, this problem will be more serious. Rollback lock release time
When Seata rolls back, it needs to delete the undo log of each node before releasing the lock in the TC memory. Therefore, if the second stage is a rollback, the time to release the lock will be longer.
Deadlock problem
Seata's introduction of global locks will increase the risk of deadlocks. However, if a deadlock occurs, it will continue to retry, and finally wait for the global lock to time out. This method is not elegant and also prolongs the occupation of the database lock. time.

Seata quick use

https://seata.io/zh-cn/docs/ops/deploy-guide-beginner.htmlDownload
the installation package

Server-side storage mode (store.mode) supports three types:
file: (default) stand-alone mode, global transaction session information is read and written in memory and the local file root.data is persisted, with high performance (default)
db: (5.7+) In high-availability mode, global transaction session information is shared through db, and the corresponding performance is poor.
Open config/file.conf
and modify mode="db"
to modify the database connection information (URL\USERNAME\PASSWORD) .
Create the database seata_server and create
a new table: You can go to the one provided by seata. Download from Resource Information:
Click to view
\script\server\db\mysql.sql
branch table stores transaction participant information

1
2 store {
    
    
3  mode = "db"
4
5  db {
    
    
6  ## the implement of javax.sql.DataSource, such as DruidDataSource(druid)/BasicDataSource(dbcp)/HikariDataSource(hik
ari) etc.
7  datasource = "druid"
8  ## mysql/oracle/postgresql/h2/oceanbase etc.
9  dbType = "mysql"
10  driverClassName = "com.mysql.jdbc.Driver"
11  url = "jdbc:mysql://192.168.65.220:3306/seata_server"
12  user = "root"
13  password = "123456"
14  minConn = 5
15  maxConn = 30
16  globalTable = "global_table"
17  branchTable = "branch_table"
18  lockTable = "lock_table"
19  queryLimit = 100
20  maxWait = 5000
21 }
22 }

redis: Supported by Seata-Server 1.3 and above, with high performance, but there is a risk of losing transaction information. Please configure the redis persistence configuration resource
directory suitable for the current scenario in advance: https://github.com/seata/seata/tree/1.3 .0/script
client
stores client-side sql scripts, parameter configuration
config-center
and each configuration center parameter import script. config.txt (including server and client, formerly known as nacos-config.txt) is a general parameter file
server
server-side database script and each Container configuration

Step 5: Configure the Nacos registration center to be responsible for transaction participants (microservices) and TC communication.
Register Seata Server to Nacos, modify the registry.conf configuration in the conf directory,
and then start the registration center Nacos Server
1 #Enter the Nacos installation directory and start Linux stand-alone
2 bin/startup.sh ‐m standalone
3 # windows stand-alone startup
4 bin/startup.bat
Step 6: Configure Nacos Configuration Center
Turing Classroom

Note: If the seata server is configured to use nacos as the configuration center, the configuration information will be read from nacos, and file.conf does not need to be configured. When configuring registry.conf on the client side
and using nacos, you should also pay attention to the group being consistent with the group in the seata server. The default group is "DEFAULT_GROUP".
Obtain /seata/script/config-center/config.txt and modify the configuration information
to configure the transaction group. Consistent with the transaction group configured on the client
#my_test_tx_group needs to be consistent with the client default needs to be consistent with the client and the cluster in the registry in registry.conf
(client properties configuration: spring.cloud.alibaba.seata.tx-service- group=my_test_tx_group)
Transaction grouping: My_test_tx_group, a remote computer room power failure tolerance mechanism,
can be customized, for example: (guangzhou, shanghai...), and the corresponding client must also set
1 seata.service.vgroup-mapping.projectA=guangzhou
default must be equal to registry. confi cluster = “default”
configuration parameters synchronized to Nacos
shell:
1 sh ${SEATAPATH}/script/config‐center/nacos/nacos‐config.sh ‐h localhost ‐p 8848 ‐g SEATA_GROUP ‐t 5a3c7d6c‐f497‐
4d68‐ a71a-2e5e3340b3ca
Parameter description:
-h: host, default value is localhost
-p: port, default value is 8848
-g: configure group, default value is 'SEATA_GROUP'
Turing Classroom
-t: tenant information, corresponding to the namespace ID field of Nacos , the default value is empty''
thin configuration
1 service.vgroupMapping.my_test_tx_group=default
2 service.default.grouplist=127.0.0.1:8091
3 service.enableDegrade=false
4 service.disableGlobalTransaction=false
5 store.mode=db
6 store. db.datasource=druid
7 store.db.dbType=mysql
8 store.db.driverClassName=com.mysql.jdbc.Driver
9 store.db.url=jdbc:mysql://127.0.0.1:3306/seata?useUnicode= true
10 store.db.user=root
11 store.db.password=root
12 store.db.minConn=5
13 store.db.maxConn=30
14 store.db.globalTable=global_table
15 store.db.branchTable=branch_table
16 store.db.queryLimit=100
17 store.db.lockTable=lock_table
18 store.db.maxWait=5000
Step 7: Start Seata Server source code startup: Execute the main method command
of io.seata.server.Server.java under the server module to start
: bin/seata-server.sh -h 127.0.0.1 -p 8091 -m db -n 1 -e test
Start Seata Server
1 bin/seata‐server.sh ‐p 8091 ‐n 1
1 bin/seata‐server.sh ‐p 8092 ‐n 2
1 bin/seata‐server.sh ‐p 8093 ‐n 3
started successfully, the default port is 8091, and
you can see in the registration center that seata‐server has been successfully registered.

Seata Client Quick Start
Declarative transaction implementation (@GlobalTransactional)
is connected to the microservice application.
Business scenario:
The user places an order. The entire business logic consists of three microservices:
Order service: Create an order based on procurement requirements.
Inventory service: Deduct the inventory quantity for a given item.
1) Start the Seata server. Seata server uses nacos as the configuration center and registration center (the previous step has been completed)
2) Configure microservices to integrate seata
. Step 1: Add pom dependency

1 <!‐‐ seata‐‐>
2 <dependency>
3 <groupId>com.alibaba.cloud</groupId>
4 <artifactId>spring‐cloud‐starter‐alibaba‐seata</artifactId>
5 </dependency>

Step 2: Add the undo_log table to the corresponding database of each microservice

1 CREATE TABLE `undo_log` (
2 `id` bigint(20) NOT NULL AUTO_INCREMENT,
3 `branch_id` bigint(20) NOT NULL,
4 `xid` varchar(100) NOT NULL,
5 `context` varchar(128) NOT NULL,
6 `rollback_info` longblob NOT NULL,
7 `log_status` int(11) NOT NULL,
8 `log_created` datetime NOT NULL,
9 `log_modified` datetime NOT NULL,
10 PRIMARY KEY (`id`),
11 UNIQUE KEY `ux_undo_log` (`xid`,`branch_id`)
12 ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

Step 5: Modify register.conf and configure nacos as registry.type&config.type. The corresponding seata server also uses nacos.
Note: You need to specify group = "SEATA_GROUP" because the Seata Server specifies group = "SEATA_GROUP", which must be consistent.

1 registry {
    
    
2  # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
3  type = "nacos"
4
5  nacos {
    
    
6  serverAddr = "localhost"
7  namespace = ""
8  cluster = "default"
9  group = "SEATA_GROUP"
10 }
11 }
12 config {
    
    
13  # file、nacos 、apollo、zk、consul、etcd3、springCloudConfig
14  type = "nacos"
15
16  nacos {
    
    
17  serverAddr = "localhost"
18  namespace = ""
19  group = "SEATA_GROUP"
20 }
21 }
22

If this problem occurs:
In most cases it is caused by configuration mismatch:
1. Check whether the seata service currently used is consistent with the version of seata in project maven
2. Check tx-service-group, nacos.cluster, Is the nacos.group parameter consistent with the configuration in Seata Server?
Tracking source code: RegistryService#lookup is implemented under the seata/discover package to obtain the service list
1 NacosRegistryServiceImpl#lookup
2 》String clusterName = getServiceGroup(key); #Get the seata server cluster Name
3 》List firstAllInstances = getNamingInstance().getAllInstances(getServiceName(), getServiceGroup(), cluster
rs)
Step 6: Modify the application.yml configuration to configure
the seata service transaction grouping, which must be consistent with the service.vgroup_mapping in the server nacos configuration center Suffix correspondence

1 server:
2  port: 8020
3
4 spring:
5  application:
6  name: order‐service
7  cloud:
8  nacos:
9  discovery:
10  server‐addr: 127.0.0.1:8848
11  alibaba:
12  seata:
13  tx‐service‐group:
14  my_test_tx_group # seata 服务事务分组
15
16  datasource:
17  type: com.alibaba.druid.pool.DruidDataSource
18  druid:
19  driver‐class‐name: com.mysql.cj.jdbc.Driver
20  url: jdbc:mysql://localhost:3306/seata_order?useUnicode=true&characterEncoding=UTF‐8&serverTimezone=Asia/Shanghai
21  username: root
22  password: root
23  initial‐size: 10
24  max‐active: 100
25  min‐idle: 10
26  max‐wait: 60000
27  pool‐prepared‐statements: true
28  max‐pool‐prepared‐statement‐per‐connection‐size: 20
29  time‐between‐eviction‐runs‐millis: 60000
30  min‐evictable‐idle‐time‐millis: 300000
31  test‐while‐idle: true
32  test‐on‐borrow: false
33  test‐on‐return: false
34  stat‐view‐servlet:
35  enabled: true
36  url‐pattern: /druid/*
37  filter:
38  stat:
39  log‐slow‐sql: true
40  slow‐sql‐millis: 1000
41  merge‐sql: false
42  wall:
43  config:
44  multi‐statement‐allow: true

Step 7: The microservice initiator (TM party) needs to add the @GlobalTransactional annotation

1 @Override
2 //@Transactional
3 @GlobalTransactional(name="createOrder")
4 public Order saveOrder(OrderVo orderVo){
    
    
5  log.info("=============用户下单=================");
6  log.info("当前 XID: {}", RootContext.getXID());
7
8 // 保存订单
9  Order order = new Order();
10  order.setUserId(orderVo.getUserId());
11  order.setCommodityCode(orderVo.getCommodityCode());
12  order.setCount(orderVo.getCount());
13  order.setMoney(orderVo.getMoney());
14  order.setStatus(OrderStatus.INIT.getValue());
15
16  Integer saveOrderRecord = orderMapper.insert(order);
17  log.info("保存订单{}", saveOrderRecord > 0 ? "成功" : "失败");
18
19 //扣减库存
20  storageFeignService.deduct(orderVo.getCommodityCode(),orderVo.getCount());
21
22 //扣减余额
23  accountFeignService.debit(orderVo.getUserId(),orderVo.getMoney());
24
25 //更新订单
26  Integer updateOrderRecord = orderMapper.updateOrderStatus(order.getId(),OrderStatus.SUCCESS.getValue());
27  log.info("更新订单id:{} {}", order.getId(), updateOrderRecord > 0 ? "成功" : "失败");
28
29 return order;
30
31 }

Guess you like

Origin blog.csdn.net/wangjunlei666/article/details/129886449