springboot整合redis+自定义注解+反射+aop实现接口限流

在应对大并发请求时,为了防止系统崩溃,文章介绍了通过定义注解和使用Redis的原子性计数器来实现接口限流的方法。当请求超过预设的并发数或速率时,系统会进行等待、排队或返回错误信息。具体实现包括定义限流注解,利用AOP进行切面处理,以及通过Redis服务进行计数和过期时间设置。

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

为什么我们要对接口进行限流呢?

因为在面对大并发大流量的请求时,突发情况下,大量的请求会将系统整垮,造成响应失败超时等状况。那为了防止出现这种情况最常见的解决方案之一就是限流,当请求达到一定的并发数或速率,就进行等待、排队、降级、拒绝服务等。

本文基于限流反射之一的计数器方式来实现限流

1.定义注解

package com.cwf.framework.limit.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Limit {
    /**
     * 资源的key,唯一
     * 作用:不同的接口,不同的流量控制
     */
    String key() default "";

    /**
     * 最多的访问限制次数
     */
    long count() default 7;

    /**
     * 过期时间也可以理解为单位时间,单位秒,默认60
     */
    long expire() default 60;


    /**
     * 提示语
     */
    String msg() default "系统繁忙,请稍后再试!";
}

2.aop+redis

利用redis 的incr 高并发 原子性计数器来计数,当请求次数超过规定次数就抛出自定义异常,全局异常捕获异常信息返回给前台

package com.cwf.framework.limit.aspectj;

import com.cwf.common.core.controller.BaseController;
import com.cwf.common.exception.base.MyException;
import com.cwf.common.utils.ip.IpUtils;
import com.cwf.framework.limit.annotation.Limit;
import com.cwf.framework.redis.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;


/**
 * 限流服务
 */
@SuppressWarnings("all")
@Slf4j
@Component
@Aspect
public class LimitAOP extends BaseController {

    @Autowired
    private RedisService redisService;

    @Pointcut("@annotation(com.cwf.framework.limit.annotation.Limit)")
    private void LimitPointcut() {

    }

    @Before("@annotation(limit)")
    public void before(JoinPoint point, Limit limit) throws ClassNotFoundException, IllegalAccessException, NoSuchFieldException {
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        assert requestAttributes != null;
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);

        assert request != null;
        String path = request.getRequestURI();
        String ip = IpUtils.getIpAddress(request);

        //获取注解信息
        String key = limit.key();
        long count = limit.count();
        String msg = limit.msg();
        long expire = limit.expire();

        String redisKey = ip+path+key+getUserId();
        Long inc = redisService.inc(redisKey);

        if (inc==1){
            redisService.expire(redisKey, expire, TimeUnit.SECONDS);
        }

        if (inc > count){
            log.error("\n{}触发限制流量",key);
            throw new MyException(msg,400);
        }



    }

}


1.使用

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值