SpringBoot利用限速器RateLimiter实现单机限流的示例代码

作者:任未然 时间:2023-04-05 19:57:50 

一. 概述

参考开源项目https://github.com/xkcoding/spring-boot-demo

在系统运维中, 有时候为了避免用户的恶意刷接口, 会加入一定规则的限流, 本Demo使用速率限制器com.xkcoding.ratelimit.guava.annotation.RateLimiter实现单机版的限流

二. SpringBootDemo

2.1 依赖

    <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

server:
  port: 8080
  servlet:
    context-path: /demo

2.3 启动类

@SpringBootApplication
public class SpringBootDemoRatelimitGuavaApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootDemoRatelimitGuavaApplication.class, args);
    }
}

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

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

@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

@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.xkcoding.ratelimit.guava.annotation.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 使用

@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", "别想一直看到我,不信你快速刷新看看~");
    }
}

来源:https://www.jianshu.com/p/6e812f307f06

标签:SpringBoot,单机,限流
0
投稿

猜你喜欢

  • 浅谈String.split()遇到空字符串的几种情况

    2021-11-24 00:18:38
  • android如何获取联系人所有信息

    2021-10-24 13:24:41
  • Java实现List集合转树形结构的示例详解

    2021-11-11 10:48:33
  • 在C#中使用OpenCV(使用OpenCVSharp)的实现

    2023-02-21 16:15:38
  • 使用Java8实现模板方法模式的改造

    2021-10-28 23:46:09
  • 桌面浮动窗口(类似恶意广告)的实现详解

    2023-04-28 06:02:27
  • 基于Android本地代码生成器详解

    2022-09-15 02:52:26
  • Java多线程实现简易微信发红包的方法实例

    2023-04-16 11:46:15
  • 小白2分钟学会Visual Studio如何将引用包打包到NuGet上

    2022-01-14 10:25:53
  • c# 判断指定文件是否存在的简单实现

    2023-10-16 01:39:54
  • springboot多环境配置文件及自定义配置文件路径详解

    2021-09-30 03:55:54
  • C++中的String的常用函数用法

    2023-03-26 17:52:45
  • Android中关于百度糯米app关闭网页或窗口的方法(99%人不知)

    2023-02-18 00:23:49
  • Mybatis之association和collection用法

    2021-10-13 10:09:10
  • 利用Thumbnailator轻松实现图片缩放、旋转与加水印

    2022-03-26 18:44:04
  • 计算机编程语言发展史

    2022-10-07 21:28:49
  • Java编程实现排他锁代码详解

    2021-06-11 06:00:23
  • C#使用NPOI将excel导入到list的方法

    2023-11-17 22:49:09
  • Java数据结构及算法实例:三角数字

    2023-08-24 17:52:25
  • Android开发中自定义 editText下划线

    2023-03-30 13:40:35
  • asp之家 软件编程 m.aspxhome.com