SpringBoot使用自定义注解+AOP+Redis实现接口限流

农民  论坛元老 | 2022-9-17 08:38:28 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 1011|帖子 1011|积分 3033

为什么要限流
系统在设计的时候,我们会有一个系统的预估容量,长时间超过系统能承受的TPS/QPS阈值,系统有可能会被压垮,最终导致整个服务不可用。为了避免这种情况,我们就需要对接口请求进行限流。
所以,我们可以通过对并发访问请求进行限速或者一个时间窗口内的的请求数量进行限速来保护系统或避免不必要的资源浪费,一旦达到限制速率则可以拒绝服务、排队或等待。 
 
限流背景
系统有一个获取手机短信验证码的接口,因为是开放接口,所以为了避免用户不断的发送请求获取验证码,防止恶意刷接口的情况发生,于是用最简单的计数器方式做了限流,限制每个IP每分钟只能请求一次,然后其他每个手机号的时间窗口限制则是通过业务逻辑进行判断。一般一些接口访问量比较大的,可能会压垮系统的,则需要加入流量限制!如:秒杀等...
 
实现限流
1、引入依赖
  1. <dependency>
  2.     <groupId>org.springframework.boot</groupId>
  3.     <artifactId>spring-boot-starter-aop</artifactId>
  4. </dependency>
  5. <dependency>
  6.     <groupId>org.springframework.boot</groupId>
  7.     <artifactId>spring-boot-starter-data-redis</artifactId>
  8. </dependency>        
复制代码
 
2、自定义限流注解
  1. @Target(ElementType.METHOD)
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Documented
  4. public @interface RateLimiter
  5. {
  6.     /**
  7.      * 限流key
  8.      */
  9.      String key() default Constants.RATE_LIMIT_KEY;
  10.     /**
  11.      * 限流时间,单位秒
  12.      */
  13.      int time() default 60;
  14.     /**
  15.      * 限流次数
  16.      */
  17.     int count() default 100;
  18.     /**
  19.      * 限流类型
  20.      */
  21.     LimitType limitType() default LimitType.DEFAULT;
  22.     /**
  23.      * 限流后返回的文字
  24.      */
  25.     String limitMsg() default "访问过于频繁,请稍候再试";
  26. }
复制代码
 
3、限流切面
  1. @Aspect
  2. @Component
  3. public class RateLimiterAspect {
  4.     private final static Logger log = LoggerFactory.getLogger(RateLimiterAspect.class);
  5.     @Autowired
  6.     private RedisUtils redisUtils;
  7.     @Before("@annotation(rateLimiter)")
  8.     public void doBefore(JoinPoint point, RateLimiter rateLimiter) throws Throwable
  9.     {
  10.         int time = rateLimiter.time();
  11.         int count = rateLimiter.count();
  12.         long total = 1L;
  13.         String combineKey = getCombineKey(rateLimiter, point);
  14.         try
  15.         {
  16.             if(redisUtils.hasKey(combineKey)){
  17.                 total = redisUtils.incr(combineKey,1);  //请求进来,对应的key加1
  18.                 if(total > count)
  19.                     throw new ServiceRuntimeException(rateLimiter.limitMsg());
  20.             }else{
  21.                 redisUtils.set(combineKey,1,time);  //初始化key
  22.             }
  23.         }
  24.         catch (ServiceRuntimeException e)
  25.         {
  26.             throw e;
  27.         }
  28.         catch (Exception e)
  29.         {
  30.             throw new ServiceRuntimeException("网络繁忙,请稍候再试");
  31.         }
  32.     }
  33.     /**
  34.      * 获取限流key
  35.      * @param rateLimiter
  36.      * @param point
  37.      * @return
  38.      */
  39.     public String getCombineKey(RateLimiter rateLimiter, JoinPoint point)
  40.     {
  41.         StringBuffer stringBuffer = new StringBuffer(rateLimiter.key());
  42.         if (rateLimiter.limitType() == LimitType.IP)
  43.         {
  44.             stringBuffer.append(IpUtils.getIpAddr(ServletUtils.getRequest())).append("-");
  45.         }
  46.         MethodSignature signature = (MethodSignature) point.getSignature();
  47.         Method method = signature.getMethod();
  48.         Class<?> targetClass = method.getDeclaringClass();
  49.         stringBuffer.append(targetClass.getName()).append("-").append(method.getName());
  50.         return stringBuffer.toString();
  51.     }
  52. }
复制代码
 
4、写一个简单的接口进行测试
  1. @RestController
  2. public class TestController {
  3.     @RateLimiter(time = 60, count = 1, limitType = LimitType.IP, limitMsg = "一分钟内只能请求一次,请稍后重试")
  4.     @GetMapping("/hello")
  5.     public ResultMsg hello() {
  6.         return ResultMsg.success("Hello World!");
  7.     }
  8. }
复制代码
 
5、全局异常拦截
  1. @RestControllerAdvice
  2. public class GlobalExceptionHandler {
  3.     private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
  4.     /**
  5.      * 业务异常
  6.      */
  7.     @ExceptionHandler(ServiceRuntimeException.class)
  8.     public ResultMsg handleServiceException(ServiceRuntimeException e, HttpServletRequest request)
  9.     {
  10.         return ResultMsg.error(e.getMessage());
  11.     }
  12.     /**
  13.      * 系统异常
  14.      */
  15.     @ExceptionHandler(Exception.class)
  16.     public ResultMsg handleException(Exception e, HttpServletRequest request)
  17.     {
  18.         return ResultMsg.error("系统异常");
  19.     }
  20. }
复制代码
 
6、接口测试
1)第一次发送,正常返回结果

 
2)一分钟内第二次发送,返回错误,限流提示
 

 
好了,大功告成啦
还有其他的限流方式,如滑动窗口限流方式(比计数器更严谨)、令牌桶等...,有兴趣的小伙伴可以学习一下
 
附源码
https://gitee.com/jae_1995/ratelimiter
 

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

农民

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表