简介
利用SpringBoot AOP在程序抛出异常时执行对应的操作,在需要的方法上打上自定义的注解,在切面中进行配置。切面接收的参数就是就是抛出的异常,自定义异常存放数据。(适合抛出异常后要进行操作的情况)
自定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SyncData {
}
自定义异常
public class SyncDataException extends RuntimeException{
/**
* 失败的impl实现类
*/
private SynChroBean synChroBean;
/**
* 失败时第几次的循环
*/
private int index;
/**
* 每页数量
*/
private int pageSize;
/**
* 总页数
*/
private int totalPage;
public SyncDataException(String message,SynChroBean synChroBean,int index,int totalPage,int pageSize) {
super(message);
this.synChroBean = synChroBean;
this.index = index;
this.pageSize = pageSize;
this.totalPage = totalPage;
}
public SynChroBean getSynChroBean() {
return synChroBean;
}
public int getTotalPage() {
return totalPage;
}
public int getIndex() {
return index;
}
public int getPageSize() {
return pageSize;
}
}
切面类
@Aspect
@Component
public class SyncDataAspect {
@Autowired
private DynamicThirdDataSourceService dynamicThirdDataSourceService;
@AfterThrowing(throwing="ex",pointcut="@annotation(SyncData)")
public void doRecoveryActions(SyncDataException ex){
//在这里重试调用
SyncDataException syncDataException = ex;
int index = syncDataException.getIndex();
SynChroBean synChroBean = syncDataException.getSynChroBean();
int pageSize = syncDataException.getPageSize();
int totalPage = syncDataException.getTotalPage();
dynamicThirdDataSourceService.synchroData(synChroBean,index,totalPage,pageSize);
}
}
使用
@SyncData //配置自定义注解
public void synchroData(SynChroBean synChroBean,int index,int totalPage,int pageSize) {
//找到对应的ServiceImpl class
Class serviceImplClass = synChroBean.getClazz();
//获取bean容器中配置类Mapper的实例
Object ThirdDataSourceMapper = context.getBean(DynamicThirdDataSourceMapper.class);
//获取bean容器中ServiceImpl的实例
TableOperateMethod tableOperateMethod = (TableOperateMethod) context.getBean(serviceImplClass);
int j = 0;
try {
for (int i = index; i <= totalPage; i++) {
j = i;
//查询出第三方表的数据List
List dataList = (List) synChroBean.getMethod().invoke(ThirdDataSourceMapper, pageSize, i*pageSize);
tableOperateMethod.execute(dataList,false);
}
//同步后删除旧数据
tableOperateMethod.deleteOldData();
} catch (Exception e) {
try {
Thread.sleep(10000);
} catch (InterruptedException interruptedException) {
interruptedException.printStackTrace();
}
//抛出自定义异常,被切面捕获
throw new SyncDataException(e.getMessage(),synChroBean,j,totalPage,pageSize);
}
}