Spring Cloud整合Seata实现TCC分布式事务模式案例(含源码)
@LocalTCC
public class BusinessService implements BusinessServiceAPI {
@Autowired
private AccountService accountService;
@Override
@TwoPhaseBusinessAction(name = "BusinessAction", commitMethod = "commit", rollbackMethod = "rollback")
public boolean prepare(BusinessActionContext actionContext, String businessAction, int amount) {
return accountService.debit(businessAction, amount);
}
public boolean commit(BusinessActionContext actionContext) {
return accountService.debit(actionContext.getActionName(), 1);
}
public boolean rollback(BusinessActionContext actionContext) {
return accountService.credit(actionContext.getActionName(), 1);
}
}
@Service
public class AccountService {
@GlobalTransactional
public boolean debit(String actionName, int amount) {
// 模拟扣款操作
System.out.println(actionName + " 扣款 " + amount + " 成功");
return true;
}
public boolean credit(String actionName, int amount) {
// 模拟补偿操作
System.out.println(actionName + " 补偿 " + amount + " 成功");
return true;
}
}
这个代码示例展示了如何在Spring Cloud应用中使用Seata实现TCC模式的分布式事务。BusinessService
类通过@LocalTCC
注解标记为TCC服务类。该类中的prepare
方法用于准备销售业务,并且通过@TwoPhaseBusinessAction
注解指定了该操作是一个两阶段的业务动作。commit
和rollback
方法分别用于提交和回滚业务。AccountService
中的debit
和credit
方法分别用于模拟扣款和补偿操作。这个例子简单明了地展示了TCC模式在实际业务中的应用。
评论已关闭