微服务下有两个类,需要做异常捕获再抛出,笔者立马想到了AOP
非微服务,只能使用代理
@Slf4j
@Aspect
@Component
public class SdkAspect {
@Pointcut("execution(* com.aspire.service.impl.XxxEncryption.*(..))")
public void enPointcut() {
}
@Pointcut("execution(* com.aspire.service.impl.XxxSignature.*(..))")
public void signPointcut() {
}
@Around("enPointcut() || signPointcut()")
public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
try {
// 调用原始方法
long start = System.currentTimeMillis();
Object result = joinPoint.proceed();
long end = System.currentTimeMillis();
logInfo(joinPoint, start, end);
return result;
} catch (Exception e) {
log.error("调用sdk异常");
throw e;
}
}
/**
* 打印信息
*
* @param joinPoint 切点
* @param start 起始时间
* @param end 结束时间
*/
private static void logInfo(ProceedingJoinPoint joinPoint, long start, long end) {
try {
// 定位方法
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
long cost = end - start;
log.info("SDK方法:{} 调用耗时: {} 毫秒", method.getName(), cost);
} catch (Exception e) {
log.error("log error {}", e);
}
}
}