前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringBoot利用限速器RateLimiter实现单机限流

SpringBoot利用限速器RateLimiter实现单机限流

作者头像
用户7741497
发布2022-03-24 10:00:47
1.2K0
发布2022-03-24 10:00:47
举报
文章被收录于专栏:hml_知识记录

一. 概述

参考开源项目https://github.com/xkcoding/spring-boot-demo 在系统运维中, 有时候为了避免用户的恶意刷接口, 会加入一定规则的限流, 本Demo使用速率限制器com.xkcoding.ratelimit.guava.annotation.RateLimiter实现单机版的限流

二. SpringBootDemo

2.1 依赖

代码语言:javascript
复制
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>

    <dependency>
      <groupId>cn.hutool</groupId>
      <artifactId>hutool-all</artifactId>
    </dependency>

    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
    </dependency>

2.2 application.yml

代码语言:javascript
复制
server:
  port: 8080
  servlet:
    context-path: /demo

2.3 启动类

代码语言:javascript
复制
@SpringBootApplication
public class SpringBootDemoRatelimitGuavaApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootDemoRatelimitGuavaApplication.class, args);
    }
}

2.4 定义一个限流注解 RateLimiter.java

注意代码里使用了 AliasFor 设置一组属性的别名,所以获取注解的时候,需要通过 Spring 提供的注解工具类 AnnotationUtils 获取,不可以通过 AOP 参数注入的方式获取,否则有些属性的值将会设置不进去。

代码语言:javascript
复制
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RateLimiter {
    int NOT_LIMITED = 0;

    /**
     * qps (每秒并发量)
     */
    @AliasFor("qps") double value() default NOT_LIMITED;

    /**
     * qps (每秒并发量)
     */
    @AliasFor("value") double qps() default NOT_LIMITED;

    /**
     * 超时时长,默认不等待
     */
    int timeout() default 0;

    /**
     * 超时时间单位,默认毫秒
     */
    TimeUnit timeUnit() default TimeUnit.MICROSECONDS;
}

2.5 代理: RateLimiterAspect.java

代码语言:javascript
复制
@Slf4j
@Aspect
@Component
public class RateLimiterAspect {
    /**
     * 单机缓存
     */
    private static final ConcurrentMap<String, com.google.common.util.concurrent.RateLimiter> RATE_LIMITER_CACHE = new ConcurrentHashMap<>();

    /**
      这里记得改成你自己注解实际的包路径,我看有些小伙伴说报错, 就是路径不对识别不到
    */
    @Pointcut("@annotation(com.**.RateLimiter)")
    public void rateLimit() {

    }

    @Around("rateLimit()")
    public Object pointcut(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        // 通过 AnnotationUtils.findAnnotation 获取 RateLimiter 注解
        RateLimiter rateLimiter = AnnotationUtils.findAnnotation(method, RateLimiter.class);
        if (rateLimiter != null && rateLimiter.qps() > RateLimiter.NOT_LIMITED) {
            double qps = rateLimiter.qps();
            // TODO 这个key可以根据具体需求配置,例如根据ip限制,或用户
            String key = method.getDeclaringClass().getName() + StrUtil.DOT + method.getName();
            if (RATE_LIMITER_CACHE.get(key) == null) {
                // 初始化 QPS
                RATE_LIMITER_CACHE.put(key, com.google.common.util.concurrent.RateLimiter.create(qps));
            }

            // 尝试获取令牌
            if (RATE_LIMITER_CACHE.get(key) != null && !RATE_LIMITER_CACHE.get(key).tryAcquire(rateLimiter.timeout(), rateLimiter.timeUnit())) {
                throw new RuntimeException("手速太快了,慢点儿吧~");
            }
        }
        return point.proceed();
    }
}

2.6 使用

代码语言:javascript
复制
@Slf4j
@RestController
public class TestController {

    /**
     * 接口每秒只能请求一次,不等待
     * @return
     */
    @RateLimiter(value = 1.0)
    @GetMapping("/test1")
    public Dict test1() {
        log.info("【test1】被执行了。。。。。");
        return Dict.create().set("msg", "hello,world!").set("description", "别想一直看到我,不信你快速刷新看看~");
    }

    /**
     * 接口每秒只能请求一次,等待一秒
     * @return
     */
    @RateLimiter(value = 1.0, timeout = 1,timeUnit = TimeUnit.SECONDS)
    @GetMapping("/test3")
    public Dict test3() {
        log.info("【test3】被执行了。。。。。");
        return Dict.create().set("msg", "hello,world!").set("description", "别想一直看到我,不信你快速刷新看看~");
    }
}

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一. 概述
  • 二. SpringBootDemo
    • 2.1 依赖
      • 2.2 application.yml
        • 2.3 启动类
          • 2.4 定义一个限流注解 RateLimiter.java
            • 2.5 代理: RateLimiterAspect.java
              • 2.6 使用
              领券
              问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档