SpringBoot AOP @AfterThrowing+自定义注解+自定义异常使用

简介

利用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);
		}
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值