@Aspect
@Component
@Slf4j
public class ControllerTimeAop {
// service层的统计日志/耗时(方法所在的包)
public static final String POINT = "execution (* cn.xy.os.contrlller.*.*(..))";
@Autowired
InterfaceSlowService interfaceSlowService;
@Pointcut("execution (public * com.xy.os.controller..*(..))")
public void controllerPointCut(){}
@Pointcut("execution (public * com.xy.os.api..*(..))")
public void apiPointCut(){}
@Around("controllerPointCut() || apiPointCut()")
public Object before(ProceedingJoinPoint joinPoint) {
Object resultData = null;
long startTime = System.currentTimeMillis();
Object[] args = joinPoint.getArgs();
try {
resultData = joinPoint.proceed(args);
} catch (Throwable e) {
log.error("获取接口返回结果信息出错 exception {}", e.getMessage());
}
long endTime = System.currentTimeMillis();
try{
RequestAttributes ra = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes sra=(ServletRequestAttributes)ra;
HttpServletRequest request = sra.getRequest();
//String url = request.getRequestURL().toString();
//HttpServletRequest httpServletRequest = ((HttpServletRequest) args[0]);
log.info("接口名称 {} 接口调用耗时 {}ms", request.getRequestURI(), endTime - startTime);
Map<String,Object> map = new HashMap<>();
Long costTime = endTime - startTime ;
map.put("cost_time", costTime);
map.put("name", request.getRequestURI());
map.put("params", request.getQueryString());
if( costTime > 500){
interfaceSlowService.addInterfaceSlow(map);
}
}catch (Exception e){
log.error("保存接口耗时信息出错 exception {}", e.getMessage());
}
return resultData;
}
}