AOP实现api接口每小时访问次数和成功失败统计

AOP拦截所有请求,获取HttpServletRequest和相应结果,并统计请求耗时,成功失败情况

@Slf4j
@Aspect
@Component
public class AccessAOP {

    public AccessAOP(RedisService redisService) {
        this.redisService = redisService;
    }

    //!是排除
    @Pointcut("execution(* com.xxx.controller.web..*.*(..)) " +
            "&& !execution(* com.xxx.VisitLogController.*(..))"+
            "&& !execution(* com.xxx.ApiLogScheduleController.*(..))"
    )
    public void controllerPointCut(){
        //access请求切面
    }

    private final RedisService redisService;

    @Around("controllerPointCut()")
    public Object process(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        ApiResult<String> result;
        String key = null;
        String uri = null;
        String user = null;
        String resultStatus = null;
        try {
            final ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (Objects.isNull(attributes)) {
                return failed("data 参数获取失败");
            }
            //获取请求的request
            HttpServletRequest request = attributes.getRequest();
            uri = request.getRequestURI();
            user = getUserInfo(request).getUser();
            //获取响应结果 我强转了下
            result = (ApiResult<String>) joinPoint.proceed(joinPoint.getArgs());
            if (result.code == 200) {
                resultStatus = "success";
            }
            long endTime = System.currentTimeMillis();
            String statisticType = getStatisticType(endTime - startTime);
            key = uri + "_" + DateUtils.getCurrentHour() + "_" + user + "_" + resultStatus + "_" + statisticType;
            //写入redis,值会累加
            redisService.hIncrementBy(DateUtils.getCurrentHour(),key);
            return  result;
        }catch (Exception e){
            long exceptionTime = System.currentTimeMillis();
            resultStatus = "failed";
            key = uri + "_" + DateUtils.getCurrentHour() + "_" + user + "_" + resultStatus + "_" + getStatisticType(exceptionTime-startTime);
            throw e;
        }finally {
            redisService.hIncrementBy(DateUtils.getCurrentHour(),key);
        }
    }

    public String getStatisticType(long time){
        if(time<1000){
            return "statistic1";
        }else if(time>1000 && time<3000){
            return "statistic2";
        }else if(time>3000 && time<5000){
            return "statistic3";
        }else {
            return "statistic4";
        }
    }
}

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值