自定义注解
案例代码
/**
* @author wangchao
* @date 2020-11-27 13:07:21
*/
@Service
public class TTestServiceImpl extends ServiceImpl<TTestMapper, TTest> implements TTestService {
@Autowired
TTestFeignClient feignClient;
@Autowired
TTest2FeignClient feignClient2;
@Override
@TxTransaction(isStart = true)
@Transactional
public boolean saveTTest() {
TTest tTest = new TTest();
tTest.setName("WC");
boolean save = this.save(tTest);
R tx = feignClient.tx();
R tx1 = feignClient2.tx();
return save;
}
}
这里首先自定义分布式事务注解,只要职责是注册事务组,用来执行最后的事务的提交或回滚。
/**
* @author WangChao
* @create 2020/11/27 7:29
*/
@Target({ElementType.METHOD, ElementType.TYPE}) //标记方法和类,接口使用
@Retention(RetentionPolicy.RUNTIME)
@Inherited //类继承关系中,子类会继承父类使用的注解中被@Inherited修饰的注解
@Documented //给标记注解生成api文档
public @interface TxTransaction {
/**
* 是否LCN事务发起方
* @return true 是:是发起方 false 否:是参与方
*/
boolean isStart() default false;
}
定义一个aop拦截器,用来拦截此注解。
/**
* @author WangChao
* @create 2020/11/27 8:14
*/
@Aspect
@Component
public class TransactionAspect implements Ordered {
@Autowired
private TxManagerInterceptor txManagerInterceptor;
@Around("@annotation(org.tx.anno.TxTransaction)")
public Object around(ProceedingJoinPoint pj) throws Throwable {
Object around = txManagerInterceptor.around(pj);
return around;
}
/**
* 这里设置的是执行顺序,1000表示在所有事务执行完后,在执行这个拦截器。具体可看我的spring-aop文章那节
* @return
*/
@Override
public int getOrder() {
return 1000;
}
}