自定义注解之限流

该文章介绍了一个基于注解的限流实现,通过@RateLimiter定义限流规则,如限流key、时间和次数。在AOP切面中,利用RedisTemplate进行限流操作,检查请求频率并抛出异常以控制访问。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

限流注解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RateLimiter {
    //限流的key
    String key() default Constants.RATE_LIMIT_KEY;

    //限流的时间
    int time() default 10;

    //限流的次数
    int count() default 1;

    //类型
    String type() default "";

    //限流后返回的文字
    String msg() default "访问太过频繁,请求稍后重试!";
}

@Aspect
@Component
@RequiredArgsConstructor
public class RateLimiterAspect {
    public static final Logger logger = LoggerFactory.getLogger(RateLimiterAspect.class);

    @Resource
    RedisTemplate redisTemplate;

    @Pointcut(value = "@annotation(rateLimiter)")
    public void pointCut(RateLimiter rateLimiter) {
    }

    @Before("pointCut(rateLimiter)")
    public void doBefore(JoinPoint joinPoint, RateLimiter rateLimiter) throws Exception {
        this.handle(joinPoint, rateLimiter);
    }

    private void handle(JoinPoint joinPoint, RateLimiter rateLimiter) throws Exception {
        //获取当前用户的id
        //拿到HttpServletRequest对象
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(requestAttributes.REFERENCE_REQUEST);

        try {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            Class<?> targetClass = method.getDeclaringClass();

            //key = ratelimiter:ip:类名
            String ip = IpUtils.getIp(request) + ":";

            StringBuffer stringBuffer = new StringBuffer(RATELIMITER);
            stringBuffer.append(ip).append(":").append(method.getName());

            String key = stringBuffer.toString();

            if (redisTemplate.hasKey(key)) {
                redisTemplate.opsForValue().increment(key);
                int num = Integer.parseInt((String) redisTemplate.opsForValue().get(key.toString()));
                if (num > rateLimiter.count()) {
                    throw new RateLimiterException("网络繁忙,请稍候再试!");
                }
            } else {
                redisTemplate.opsForValue().set(key, "1", Long.valueOf(rateLimiter.time()), TimeUnit.SECONDS);
            }
        } catch (RateLimiterException e) {
            throw new RateLimiterException("网络繁忙,请稍候再试");
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new Exception();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值