XA Integration Principle
Overview
Java implements XA (eXtended Architecture) distributed transaction model through defining JTA (Java Transaction API) interface. JTA specification mainly contains three core components:
- TransactionManager: Transaction coordinator, responsible for coordinating and managing global transactions
- XAResource: Resource manager interface, implemented by each resource vendor
- UserTransaction: Simple transaction interface for developers
Problems with Traditional Architecture
- High deployment cost: Must rely on heavyweight application server
- Complex O&M: Requires professional personnel for configuration and maintenance
- High resource consumption: Full application server occupies more system resources
Embedded Transaction Manager
Modern distributed systems adopt embedded transaction manager solutions:
- Provides services as lightweight jar package
- Can be directly integrated with application process
- Typical representatives: Atomikos, Bitronix
ShardingSphere XA Transaction Core Features
- Cross-database XA transaction support
- Strong consistency guarantee mechanism: Uses standard two-phase commit protocol (2PC)
- Fault recovery capability: Built-in transaction log persistence mechanism
- Extensible transaction manager integration: Based on SPI mechanism
- Diversified connection pool support
- Multiple access methods: Spring Boot Starter, Namespace approach
Execution Flow
Transaction Initiation Phase
- Application calls begin() method to start distributed transaction
- XAShardingTransactionManager initializes XA transaction context
- Creates corresponding global transaction instance
XA Resource Registration
- Create corresponding database connection for each physical shard SQL
- Register each physical connection’s XAResource to current XA transaction
- Send XAResource.start command to database
Commit/Rollback Flow
Commit Phase
- Transaction boundary marking: Call XAResource.end instruction
- Prepare phase: Send prepare instruction to all XAResources
- Resolution phase:
- All votes pass: Send commit instruction
- Veto: Trigger rollback instruction
Exception Handling Mechanism
- Operation atomicity: Either all commit successfully, or all roll back
- Data strong consistency: All participants reach final consistent state
- Fault recovery: Ensures interrupted transactions can be recovered through persisted logs