0
# Core Transaction Management
1
2
The core transaction management capability provides automatic configuration of Seata's global transaction scanning and management. This is the foundation that enables distributed transaction coordination across microservices by automatically detecting `@GlobalTransactional` annotations and managing the transaction lifecycle.
3
4
## Installation and Setup
5
6
This capability is automatically enabled when you include the seata-spring-boot-starter dependency and is active by default:
7
8
```properties
9
# Enable Seata auto-configuration (default: true)
10
seata.enabled=true
11
12
# Required: Application identifier for transaction coordination
13
seata.application-id=my-application
14
15
# Required: Transaction service group name
16
seata.tx-service-group=my-tx-group
17
```
18
19
## Core Components
20
21
### GlobalTransactionScanner Bean
22
23
The central component that scans for `@GlobalTransactional` annotations and manages distributed transactions.
24
25
```java { .api }
26
@Bean
27
public static GlobalTransactionScanner globalTransactionScanner(
28
SeataProperties seataProperties,
29
FailureHandler failureHandler,
30
ConfigurableListableBeanFactory beanFactory,
31
List<ScannerChecker> scannerCheckers
32
);
33
```
34
35
**Parameters:**
36
- `seataProperties`: Main Seata configuration properties
37
- `failureHandler`: Handler for transaction failure scenarios
38
- `beanFactory`: Spring bean factory for component registration
39
- `scannerCheckers`: List of custom scanner checkers for validation
40
41
**Returns:** `GlobalTransactionScanner` - The configured transaction scanner
42
43
### FailureHandler Bean
44
45
Handles transaction failure scenarios and provides customizable failure handling logic.
46
47
```java { .api }
48
@Bean("failureHandler")
49
public FailureHandler failureHandler();
50
```
51
52
**Returns:** `DefaultFailureHandlerImpl` - Default implementation of failure handling
53
54
## Transaction Annotation Usage
55
56
### @GlobalTransactional Annotation
57
58
Use this annotation on methods that should be executed within a distributed transaction:
59
60
```java
61
import io.seata.spring.annotation.GlobalTransactional;
62
import org.springframework.stereotype.Service;
63
64
@Service
65
public class BusinessService {
66
67
@GlobalTransactional(rollbackFor = Exception.class)
68
public void handleBusinessLogic() {
69
// This method will be executed within a global transaction
70
// All database operations and remote service calls
71
// will be coordinated as a single distributed transaction
72
73
orderService.createOrder(); // Service call 1
74
paymentService.processPayment(); // Service call 2
75
inventoryService.updateStock(); // Service call 3
76
77
// If any operation fails, all will be rolled back
78
}
79
80
@GlobalTransactional(
81
timeoutMills = 300000, // 5 minutes timeout
82
name = "create-order-transaction",
83
rollbackFor = {BusinessException.class, DataException.class}
84
)
85
public void createOrderWithCustomSettings() {
86
// Transaction with custom timeout and rollback rules
87
}
88
}
89
```
90
91
### @GlobalTransactional Properties
92
93
```java { .api }
94
public @interface GlobalTransactional {
95
// Transaction timeout in milliseconds (default: 60000)
96
int timeoutMills() default 60000;
97
98
// Transaction name for identification
99
String name() default "";
100
101
// Exception types that trigger rollback
102
Class<? extends Throwable>[] rollbackFor() default {};
103
104
// Exception types that do not trigger rollback
105
Class<? extends Throwable>[] noRollbackFor() default {};
106
107
// Transaction propagation behavior
108
Propagation propagation() default Propagation.REQUIRED;
109
110
// Transaction isolation level
111
int lockRetryInterval() default 0;
112
113
int lockRetryTimes() default -1;
114
}
115
```
116
117
## Configuration Properties
118
119
### Transaction Scanning Configuration
120
121
Control which beans and packages are scanned for global transactions:
122
123
```properties
124
# Packages to scan for @GlobalTransactional annotations
125
seata.scan-packages=com.example.service,com.example.controller
126
127
# Bean names to exclude from transaction scanning
128
seata.excludes-for-scanning=excludedService,testService
129
130
# Additional scanning configuration
131
seata.disable-global-transaction=false
132
```
133
134
### Scanner Properties in SeataProperties
135
136
```java { .api }
137
public class SeataProperties {
138
// Packages to scan for global transactions
139
private String[] scanPackages = {};
140
141
// Bean names to exclude from scanning
142
private String[] excludesForScanning = {};
143
144
// Note: disableGlobalTransaction property is not present in actual implementation
145
}
146
```
147
148
## Auto-Configuration Details
149
150
The core transaction management is configured through `SeataAutoConfiguration`:
151
152
```java { .api }
153
@ConditionalOnProperty(prefix = "seata", name = "enabled", havingValue = "true", matchIfMissing = true)
154
@AutoConfigureAfter({SeataCoreAutoConfiguration.class})
155
public class SeataAutoConfiguration {
156
157
@Bean("failureHandler")
158
@ConditionalOnMissingBean(FailureHandler.class)
159
public FailureHandler failureHandler();
160
161
@Bean
162
@DependsOn({"springApplicationContextProvider", "failureHandler"})
163
@ConditionalOnMissingBean(GlobalTransactionScanner.class)
164
public static GlobalTransactionScanner globalTransactionScanner(
165
SeataProperties seataProperties,
166
FailureHandler failureHandler,
167
ConfigurableListableBeanFactory beanFactory,
168
@Autowired(required = false) List<ScannerChecker> scannerCheckers
169
);
170
}
171
```
172
173
## Integration with Spring Transaction Management
174
175
The global transaction scanner integrates seamlessly with Spring's existing transaction management:
176
177
```java
178
@Service
179
@Transactional // Spring's local transaction
180
public class OrderService {
181
182
@GlobalTransactional // Seata's distributed transaction
183
public void processOrder() {
184
// This method participates in both local and distributed transactions
185
// Local @Transactional ensures ACID within this service
186
// @GlobalTransactional coordinates with other services
187
188
saveOrderToDatabase(); // Local transaction
189
callPaymentService(); // Distributed transaction branch
190
callInventoryService(); // Distributed transaction branch
191
}
192
}
193
```
194
195
## Transaction Lifecycle
196
197
1. **Transaction Start**: `@GlobalTransactional` method invocation triggers global transaction creation
198
2. **Branch Registration**: Each participating resource (database, message queue) registers as a transaction branch
199
3. **Business Execution**: All business logic executes within the global transaction context
200
4. **Two-Phase Commit**:
201
- Phase 1: All branches prepare and report status
202
- Phase 2: Commit if all branches succeed, rollback if any fail
203
5. **Transaction End**: Global transaction is completed and resources are cleaned up
204
205
## Error Handling
206
207
### Custom Failure Handler
208
209
Implement custom failure handling logic:
210
211
```java
212
@Component
213
public class CustomFailureHandler implements FailureHandler {
214
215
@Override
216
public void onBeginFailure(GlobalTransaction tx, Throwable cause) {
217
// Handle transaction begin failures
218
log.error("Transaction begin failed: {}", tx.getXid(), cause);
219
}
220
221
@Override
222
public void onCommitFailure(GlobalTransaction tx, Throwable cause) {
223
// Handle transaction commit failures
224
log.error("Transaction commit failed: {}", tx.getXid(), cause);
225
// Send alert, trigger compensation, etc.
226
}
227
228
@Override
229
public void onRollbackFailure(GlobalTransaction tx, Throwable cause) {
230
// Handle transaction rollback failures
231
log.error("Transaction rollback failed: {}", tx.getXid(), cause);
232
}
233
}
234
```
235
236
## Performance Considerations
237
238
- **Transaction Timeout**: Set appropriate timeout values based on business requirements
239
- **Scanning Scope**: Limit scan packages to improve startup performance
240
- **Bean Exclusions**: Exclude beans that don't need transaction management
241
- **Failure Handling**: Implement efficient failure handlers to avoid blocking resources
242
243
## Troubleshooting
244
245
### Common Issues
246
247
1. **Transaction Not Starting**: Check `seata.enabled=true` and proper annotation usage
248
2. **Scanner Not Finding Methods**: Verify packages are included in `seata.scan-packages`
249
3. **Performance Issues**: Review scanning configuration and exclude unnecessary beans
250
4. **Transaction Timeout**: Adjust `timeoutMills` in `@GlobalTransactional` annotation
251
252
### Debug Configuration
253
254
```properties
255
# Enable debug logging for transaction management
256
logging.level.io.seata=DEBUG
257
logging.level.io.seata.spring.annotation=DEBUG
258
259
# Transaction scanner debug information
260
seata.client.log.exception-rate=100
261
```