动态代理:
1.JDK动态代理:利用拦截器(拦截器必须实现InvocationHanlder)加上反射机制生成一个实现代理接口的匿名类,在调用具体方法前调用InvokeHandler来处理。
2.CGLIB动态代理:利用ASM开源包,对代理对象类的class文件加载进来,通过修改其字节码生成子类来处理。
注:当AOP切面应用在以抽象类为父类的策略模式中,当策略模式的实现类,需要调用父类的公用方法,并且使用AOP时,需要代理当前方法即可
AIO切面编程使用到的所有注解
/**
* @ClassName ERPRollBackException
* @Description ERP重试异常
* @Author zhe.liu
* @Date 2021/9/1 16:23
* @Version 1.0
**/
public class ERPRollBackException extends Throwable {
//默认构造器
public ERPRollBackException() {
}
//带有详细信息的构造器,信息存储在message中
public ERPRollBackException(String message) {
super(message);
}
}
/**
* 接口重试注解
* 1.这里要注意入参会重复使用,set的值会保留
* @author liu.zhe
*/
//@Retention: 定义注解的保留策略,
@Retention(RetentionPolicy.RUNTIME)// 注解会在class字节码文件中存在,在运行时可以通过反射获取到
//@Target:定义注解的作用目标
@Target({ElementType.METHOD,ElementType.PARAMETER})// 方法和方法参数
@Documented//说明该注解将被包含在javadoc中
public @interface RetryProcess {
//重试的次数,默认3次
int value() default 3;
/**
* 接口名
*/
String apiName();
/**
* 重试失败是否发邮件
* @return
*/
boolean isRetryFailSendEmail() default true;
}
/**
* ERP请求工具类切面
* 这里所有公共方法都应该是对位的接口,公共方法会经过切面:
* 失败重试三次失败发邮件
* @author liu.zhe
*/
@Aspect
@Component
public class ERPRollBackUtil {
@Resource
private AlarmNotification alarmNotification;
@Around(value = "@annotation(RetryProcess)")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
LogUtil.info("ERP接口,开始调用,入参:{}", JSON.toJSONString(Arrays.toString(joinPoint.getArgs())));
try {
Object ret = joinPoint.proceed();
LogUtil.info("ERP接口,结束调用,出参:{}", JSON.toJSONString(ret));
return ret;
} catch (Throwable ex) {
if(ex instanceof NoHttpResponseException || ex instanceof SocketTimeoutException){
LogUtil.error("ERP接口,调用异常", JSON.toJSONString(ex));
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
RetryProcess retryProcess = methodSignature.getMethod().getAnnotation(RetryProcess.class);
if(retryProcess != null){
return runThrowing(joinPoint, ex, 1, retryProcess);
}
}
throw ex;
}
}
public Object runThrowing(JoinPoint point, Throwable ex, Integer nowCount, RetryProcess retryProcess) throws Throwable {
if (nowCount > retryProcess.value()) {
if (retryProcess.isRetryFailSendEmail()){
// 发邮件
alarmNotification.sendNotice("ERP重试三次失败!",JSON.toJSONString(Arrays.toString(point.getArgs())));
}
throw ex;
}else {
LogUtil.info("ERP请求 开始重试第" + nowCount);
try {
Thread.sleep((long) Math.random() * 1000);
//获取需要重试的方法
long time1=System.currentTimeMillis();
MethodInvocationProceedingJoinPoint methodPoint = ((MethodInvocationProceedingJoinPoint) point);
long time2=System.currentTimeMillis();
LogUtil.info("同步ErpDockingImpl耗时:"+(time2-time1)/1000+"s");
//开始重试
return methodPoint.proceed();
} catch (Throwable throwable) {
LogUtil.error("ERP请求 重试失败", JSON.toJSONString(throwable));
//重试次数++
return runThrowing(point, ex, ++nowCount, retryProcess);
}
}
}
}