1. Basic use of Seata
Environment construction:
- Download Seata: You canSeata official websiteOr get the latest version on GitHub.
- Start Seata Server: After downloading Seata, configure and start Seata Server. Seata provides a default Nacos configuration center, and other configuration centers can also be used.
Introduce dependencies:
- In microservice applications, Seata's related dependencies can be introduced through Maven or Gradle.
<dependency> <groupId></groupId> <artifactId>seata-spring-boot-starter</artifactId> <version>1.6.1</version> <!-- Select the latest version as needed --> </dependency>
Configure Seata
- Before using global transactions, you need to make sure that Seata Server is started and that the application's
Correct configuration
seata: tx-service-group: my_test_tx_group # Transaction grouping service: vgroup-mapping: my_test_tx_group: default enable-auto-data-source-proxy: true # Automatically proxy data sources registry: type: nacos # Registration Center Type nacos: server-addr: 127.0.0.1:8848 # Nacos Address namespace: public group: SEATA_GROUP config: type: nacos nacos: server-addr: 127.0.0.1:8848 namespace: public group: SEATA_GROUP
Use in global transactions@GlobalTransactional
- Control of global transactions needs to be added to the method
@GlobalTransactional
to ensure that the method and all subtransactions called by Seata are managed uniformly.
import ; import ; import ; @Service public class OrderService { @Autowired private StockService stockService; @Autowired private PaymentService paymentService; @GlobalTransactional(name = "order-create", rollbackFor = ) public void createOrder(String userId, String productId, int amount) { // Deduct inventory (productId, amount); // Process payment (userId, amount); // Insert the order record ("Order creation was successful!"); } }
Use in branch transactions@Transactional
- Seata In global transactions, all database operations will automatically become branch transactions.
- exist
StockService
middle:
import ; import ; @Service public class StockService { @Transactional public void deductStock(String productId, int amount) { // Perform database inventory deduction operation ("Inventory deduction succeeded!"); } }
AlthoughStockService
Still using local transactions@Transactional
, but because@GlobalTransactional
In the context of global transactions, Seata automatically proxies and manages its transactions
Second, the working principle of Seata
Seata by introductionGlobal transaction managementandBranch transactionsto solve the transaction consistency problem in distributed systems.
It uses similar to that in traditional database transactionsTwo-Phase Commit (2PC, Two-Phase Commit)Protocols to ensure the atomicity of transactions.
Two-stage submission (2PC) process
Seata uses a two-stage commit protocol (2PC) to ensure consistency of distributed transactions. The following is the detailed process for the second phase submission:
1. Phase 1: Transaction Preparation (Try Stage)
- Global transaction begins: The client application initiates a request to the Seata Server, and Seata will generate a global transaction ID (XID) and return it to the client application. Global transaction identity is used to track the entire distributed transaction.
// Start global transactionsGlobalTransaction tx = (); ();
- Branch transaction registration: After each participant (microservice) starts, it registers itself as a branch transaction with Seata Server, and Seata Server will assign a unique transaction branch ID (Branch ID) to each branch transaction.
- Try stage: Each microservice will executeTry Operation, that is, it is ready to perform local transaction operations, but does not submit data. For example, update records in a database without committing them.
-
Perform database operations: Each participating subtransaction will perform a database update, but will not actually commit, but will enter
prepare
state (for AT mode, this means undo_log is generated).
2. Phase 2: Commit or Rollback
Commit:
- Seata Server notifies all branch transactions to commit transactions after receiving the global transaction submission request.
- Branch transaction submits database operation (delete
undo_log
)。
Rollback:
- If Seata Server finds that a branch transaction fails to execute, it notifies all committed branch transactions to rollback and restore
undo_log
Recorded data.
Three, Seata's four transaction modes
1. AT mode (automatic transaction mode)
The AT (Auto Transaction) mode is the most commonly used distributed transaction mode in Seata. It is suitable for scenarios where conventional CRUD (add, delete, modify, and check) operations are performed on the database, especially simple SQL operations.
Features:
- automation: The AT pattern is automatically proxyed on every operation of the database, and developers do not need to explicitly write transaction commits and rollback operations. Seata will automatically insert undo logs, automatically restore the original state of the database when the transaction is rolled back.
- No business code changes are required: The key advantage of the AT model is that developers do not need to modify existing business code. With Seata automatically managing transactions, developers only need to ensure that the database supports undo logs (such as MySQL, Oracle, etc.).
- Applicable to database operations only:AT mode is suitable for standard database operations, and it depends on the database's logging and undo logging mechanisms.
How it works:
- Try stage:Seata intercepts the database update operation and records the undo log, but does not submit it immediately. At this time, the data in the database has not been really modified, but the "rollback" information is retained.
- Commit stage: When a global transaction is committed, Seata will finally confirm that all data modifications are submitted by coordinating all branch transactions.
- Rollback Stage: If the global transaction fails, the data will be restored by rolling back all branch transactions.
Applicable scenarios:
- Suitable for most microservice scenarios, especially business logic that directly relies on database operations, Seata will automatically control transactions.
2. TCC mode (Try-Confirm-Cancel)
The TCC (Try-Confirm-Cancel) model is a compensation-based distributed transaction model, which is suitable for scenarios where business operations are relatively complex and involve multiple services. Unlike automatic submission and rollback in AT mode, TCC mode requires developers to implement it explicitly.Try、ConfirmandCancelThese three stages.
Features:
- Precise control: Developers need to write Try, Confirm and Cancel methods that can accurately control transaction operations at each stage.
- High flexibility: TCC mode is suitable for complex business operations, especially those scenarios where resource locking, state updates, and external system calls are required.
- Manual compensation: The key to TCC mode is the compensation mechanism. If an operation fails, the previous resource occupation or status change needs to be cancelled through the Cancel operation.
How it works:
- Try stage: Perform actual business operations, but will not submit (for example, locking resources, withholding funds). At this time, the operation is idempotent and does not change the system state.
- Confirm Phase: If the Try stage is successful, the Confirm stage will submit an operation to confirm that the business operation is completed (for example, actual deduction, final inventory update).
- Cancel stage: If the Try phase fails or a branch transaction fails, perform a Cancel operation to revoke the previous operation (for example, unlocking resources, refund).
Applicable scenarios:
- Long-term business execution: For example, complex cross-service operations such as payment and inventory deduction require an explicit compensation mechanism.
- The final consistency of the operation must be ensured: TCC is able to handle collaboration between services and ensures that each service has a clear idea of when to commit or roll back the transaction.
3. SAGA mode
SAGA (Long Transaction Mode) is a distributed transaction processing model suitable for long transactions across multiple microservices. Unlike TCC mode, SAGA mode ensures consistency by splitting long transactions into multiple small transactions, each small transaction has a Compensating Transaction for rollback operations.
Features:
- Long business split: Split large transactions into a series of small transactions, each small transaction can be committed or rolled back independently.
- Compensation mechanism: Each small transaction needs to implement a compensation transaction. When a transaction fails, the previous operation is revoked by compensating the transaction.
- Can be executed asynchronously: Each sub-transaction can be executed independently and can be executed asynchronously, without the need to lock resources like TCC.
How it works:
- Sub-business: Split the global transaction into multiple sub-transactions, each sub-transaction performs independent operations (such as payment, inventory deduction, etc.).
- Compensation operation: Each sub-transaction has a corresponding compensation operation. If a sub-transaction fails, perform the compensation operation to cancel the previous operation.
- Global transaction ends: When all sub-transactions are executed successfully, the entire SAGA transaction is terminated; if a sub-transaction fails, it will be rolled back according to the compensation rules.
Applicable scenarios:
- Long-term transactions across multiple services: For example, order creation, payment, delivery and other operations.
- Tolerate partial failure scenarios: The SAGA mode is suitable for scenarios in which some operations in a business process fail and can be repaired through a compensation mechanism.
4. XA mode (native distributed transactions)
The XA pattern is a traditional distributed transaction protocol based onXA Protocol, is a highly consistent distributed transaction model. Seata's XA pattern requires participants to support XA transaction protocols such as databases, message queues, etc.
Features:
- Strong consistency:XA pattern is the strictest distributed transaction protocol, ensuring the ultimate consistency of all distributed transactions.
- Two-stage submission protocol (2PC): Similar to AT mode, XA mode also uses the 2PC protocol to manage transaction consistency.
- Rely on the support of the underlying database: A database that supports XA transactions (for example, MySQL, Oracle, etc.) must be used.
How it works:
- Phase 1 (Prepare): All participants are ready to submit transactions, but do not submit them.
- Phase 2 (Commit/Rollback): commit the transaction if all participants are ready, otherwise the transaction will be rolled back.
Applicable scenarios:
- Scenarios that strictly require strong consistency: For example, bank transfers and other services that require extremely high transaction consistency.
Summarize
Seata supports the following four distributed transaction modes:
- AT mode: Suitable for standard database operations, automatically manage transactions, and is suitable for scenarios that do not involve complex business logic.
- TCC mode: Suitable for complex businesses across multiple services, requiring manual compensatory logic.
- SAGA mode: Suitable for long transactions, suitable for scenarios where split into multiple sub-transactions, each sub-transaction can be rolled back independently.
- XA mode: Strictly consistent distributed transaction protocol, suitable for scenarios that require strong consistency, such as financial transactions.
The above is personal experience. I hope you can give you a reference and I hope you can support me more.