自定义注解实现接口限流

自定义注解实现接口限流

场景:限制验证码在单位时间内的访问次数
实现流程:自定义一个注解,注解内包含访问的次数与单位时间。通过AOP进行切面拦截,获取注解内的次数和时间,获取请求的uri与访问者ip。组成redis的key。
使用redis将key进行原子性自增1.如果返回的是1.则设置过期时间,之后的访问直接incr即可。但是这种方式存在问题,不是原子性的,所以需要采用原子性的设置key和过期时间。
Redis官方目前set命令已经支持了set的时候指定是nx,并且设置过期时间合并成了一条指令,保证了原子性。
因此采用setIfAbsent()API进行设置。如果返回的true。代表首次设置key。如果已经存在,则返回false。代表key已经存在。则使用incr进行自增即可。

代码实现

/**
 * 处理多次请求问题,限制指定时间内只能访问的次数
 */
@Aspect
@Component
public class ReqLimitSAspect {
    @Autowired
    private RedisTemplate redisTemplate;

    @Around("@annotation(com.tute.edu.planetcommunity.annotation.ReqLmit)")
    public Object hanlderReqLimit(ProceedingJoinPoint point) {
        MethodSignature methodSignature = (MethodSignature) point.getSignature();
        ReqLmit annotation = methodSignature.getMethod().getAnnotation(ReqLmit.class);
        long count = annotation.count();
        int time = annotation.time();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        //获取访问者的ip
        //获取访问的uri
        String requestURI = request.getRequestURI();
        String ipAddr = IpUtils.getIpAddr(request);
        String key = "req:limit:" + ipAddr + ":" + requestURI;
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(key, 1, time, TimeUnit.SECONDS);
        Long countIncr=0L;
        if (!aBoolean)   {
             countIncr = redisTemplate.opsForValue().increment(key);
        }
        if (countIncr > count) {
            throw new CustomException("调用频繁,请稍后再试!");
        }
        try {
            return point.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return null;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值