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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值