千家信息网

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

发表于:2026-11-04 作者:千家信息网编辑
千家信息网最后更新 2026年11月04日,SpringBoot利用限速器RateLimiter怎么实现单机限流,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。一. 概述参考开源项目
千家信息网最后更新 2026年11月04日SpringBoot利用限速器RateLimiter怎么实现单机限流

SpringBoot利用限速器RateLimiter怎么实现单机限流,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

一. 概述

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

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

二. SpringBootDemo

2.1 依赖

          org.springframework.boot      spring-boot-starter-web              org.springframework.boot      spring-boot-starter-aop              cn.hutool      hutool-all              com.google.guava      guava    

2.2 application.yml

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

2.3 启动类

@SpringBootApplicationpublic 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)@Documentedpublic @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@Componentpublic class RateLimiterAspect {    /**     * 单机缓存     */    private static final ConcurrentMap 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@RestControllerpublic 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", "别想一直看到我,不信你快速刷新看看~");    }}

springboot是什么

springboot一种全新的编程规范,其设计目的是用来简化新Spring应用的初始搭建以及开发过程,SpringBoot也是一个服务于框架的框架,服务范围是简化配置文件。

看完上述内容,你们掌握SpringBoot利用限速器RateLimiter怎么实现单机限流的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注行业资讯频道,感谢各位的阅读!

单机 注解 接口 限速 限速器 内容 属性 方法 更多 框架 用户 问题 别想 服务 配置 束手无策 为此 代码 令牌 全新 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 哈尔滨大商圈互联网科技有限公司 A股互联网金融科技公司 互联网科技有限公司经营范围 互联网科技未来 贷财互联网科技 极限挑战互联网科技 腾讯科技 互联网女皇 创业天下互联网科技有限公司 全球顶尖互联网科技公司 烟台灵鸽互联网科技有限公司 工业互联网山东科技大学 浙南科技城互联网大厦招聘 互联网相关科技技术 互联网科技融合创新 上海乐五互联网科技有限公司 长沙渺峰互联网科技有限公司 银川新华互联网科技学校原画 安徽零酒互联网科技有限公司 互联网的科技体现在哪里 颐高云石互联网科技 金融科技创新监管互联网金融 易通互联网络科技有限公司 广州凡科互联网科技 上海万想互联网科技 互联网科技网站 佳云科技和互联网广告 哈尔滨屹滨互联网科技有限公司 浙南科技城互联网大厦招聘 互联网科技数字货币 珠海东科互联网科技有限公司
0