AOP實現接口耗時監控

@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;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章