springboot使用aop实现接口调用统计

2 篇文章 0 订阅

使用aop统计接口调用次数,次数存储在redis中,超限会拦截,接口不被调用

定义注解类

/**
 * ApiCallAnnotation
 * 接口调用次数监控
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ApiCallAnnotation {
    String name() default "";
}

定义处理类

@Aspect
@Component
public class ApiCallAdvice{
    @Autowired
    private RedisTemplate redisTemplate;
    private final static String DATE_FORMAT = "yyyy-MM-dd";
    @Pointcut("@annotation(com.meiya.phonecloud.platform.annotation.ApiCallAnnotation)")
    public void collect(){

    }

    /**
     * 接口调用之前次数限制
     * @param point
     */
    @Before("collect()")
    public void doBefore(JoinPoint point){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        //获取接口设置的限制次数
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        ApiCallAnnotation annotation = method.getAnnotation(ApiCallAnnotation.class);
        String value = annotation.name();
        String redisKey = getRedisKey(attributes);
        if(redisTemplate.hasKey(redisKey)){
            int count = Integer.parseInt(redisTemplate.opsForValue().get(redisKey).toString());
            if(StringUtils.isNotBlank(value)){
                if(count==Integer.parseInt(value)){
                    throw new Exception("超出访问次数");
                }
            }
        }

    }

    /**
     * 接口调用之后添加次数
     */
    @AfterReturning
    public void AfterReturning(){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String redisKey = getRedisKey(attributes);
        //获取key,如果存在加1,如果不存在设置key,并设置过期时间为1天
        if(redisTemplate.hasKey(redisKey)){
            redisTemplate.opsForValue().increment(1);
        }else{
            redisTemplate.opsForValue().set(redisKey,1,1L, TimeUnit.DAYS);
        }
    }

    public String getRedisKey(ServletRequestAttributes attributes){
        HttpServletRequest request = attributes.getRequest();
        String uri = request.getRequestURI();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_FORMAT);
        LocalDateTime now = LocalDateTime.now();
        String date = formatter.format(now);
        String key = uri+"_"+date;
        return key;
    }
}

在需要拦截的接口上添加注释

@ApiCallAnnotation(name="10")
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值