package org.deryck.file.service.Impl;
import io.seata.rm.tcc.api.BusinessActionContext;
import lombok.extern.slf4j.Slf4j;
import org.deryck.file.service.TccService;
import org.springframework.stereotype.Service;
@Service
@Slf4j
public class TccServiceImpl implements TccService {
@Override
public boolean prepare(BusinessActionContext businessActionContext, String param1, String param2) {
// 准备阶段逻辑
log.info("Prepare with param1: " + param1 + " and param2: " + param2);
return true;
}
@Override
public boolean commit(BusinessActionContext businessActionContext) {
// 提交阶段逻辑
log.info("Commit with context: " + businessActionContext);
return true;
}
@Override
public boolean rollback(BusinessActionContext businessActionContext) {
// 回滚阶段逻辑
log.info("Rollback with context: " + businessActionContext);
return true;
}
}
package org.deryck.file.service;
import io.seata.rm.tcc.api.BusinessActionContext;
import io.seata.rm.tcc.api.BusinessActionContextParameter;
import io.seata.rm.tcc.api.LocalTCC;
import io.seata.rm.tcc.api.TwoPhaseBusinessAction;
@LocalTCC
public interface TccService {
@TwoPhaseBusinessAction(name = "TccService", commitMethod = "commit", rollbackMethod = "rollback")
boolean prepare(BusinessActionContext businessActionContext,
@BusinessActionContextParameter(paramName = "param1") String param1,
@BusinessActionContextParameter(paramName = "param2") String param2);
boolean commit(BusinessActionContext businessActionContext);
boolean rollback(BusinessActionContext businessActionContext);
}
package org.deryck.file.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import io.seata.spring.annotation.GlobalTransactional;
@Service
public class BusinessService {
@Autowired
private TccService tccService;
@GlobalTransactional
public void doBusiness(String param1, String param2) {
// 调用TCC的prepare方法
boolean result = tccService.prepare(null, param1, param2);
if (result) {
// 业务逻辑
System.out.println("Business logic executed successfully.");
} else {
throw new RuntimeException("Business logic failed.");
}
}
}