This topic describes how to modify a local distributed transaction client to enable unitized capabilities.
This feature applies only to environments that support the LDC unitized architecture.
DTX service configuration
You can add the Maven dependency:
<dependency> <groupId>com.alipay.sofa</groupId> <artifactId>dtx-enterprise-sofa-boot-starter</artifactId> <version>${dtx.version}</version> </dependency>Service configuration:
<bean id="dtxService" class="com.alipay.dtx.client.core.api.impl.DtxServiceImpl"/>
Initiator configuration
You can configure a Spring transaction template for the initiator application. The following code shows an example.
<!--Declare a new transaction template-->
<bean id="transactionTemplate"class="org.springframework.transaction.support.TransactionTemplate">
<property name="transactionManager" ref="transactionManager"/>
<property name="propagationBehaviorName">
<value>PROPAGATION_REQUIRES_NEW</value>
</property>
</bean>In the initiator's Spring transaction template, you can call the dtxService.start(bizType, bizId, userId, context) method to start a distributed transaction. Do not use the [@DtxTransaction](#) annotation. The userId parameter is the routing parameter for service and database routing in the unitized architecture.
public class YourClass {
public void yourMethod(yourParams) {
transactionTemplate.execute(newTransactionCallback() {
@Override
public Object doInTransaction (TransactionStatus status){
// Start the distributed transaction.
dtxService.start(bizType, bizId, userId, context)
try {
// Call the phase-one try method of the TCC1 participant. The first parameter is the user ID. Pass null to the BusinessActionContext parameter.
TCC1. try (userId,params1,null) ;
// Call the phase-one try method of the TCC2 participant. The first parameter is the user ID. Pass null to the BusinessActionContext parameter.
TCC2. try (userId,params2,null) ;
// If the method returns normally, the transaction is committed.
} catch (Throwable t) {
// If an exception occurs, the transaction is rolled back.
throw t;
}
}
});
}
}Implement the status check service for the initiator
If the transaction status is uncertain, the DTX server uses a status check service to query the initiator for the transaction status. You can implement the com.alipay.dtx.client.core.api.ActivityStateResolver interface in the initiator. In the isDone method, return the transaction status: 0 for unknown, 1 for committed, or 2 for rolled back.
public class ActivityStateResolverImpl implements com.alipay.dtx.client.core.api.ActivityStateResolver {
@Override
public int isDone(String businessType, String businessId) {
System.out.println("Status check, businessType:" + businessType + ", businessId" + businessId);
return ActivityStateResolver.NOT_DONE | ActivityStateResolver.DONE;
}
}You can configure the transaction check service as a Spring bean:
<bean id="activityStateResolver" class="com.xxx.ActivityStateResolverImpl"/>