news 2026/4/16 13:34:07

Spring Cloud Gateway 实现API接口细粒度的限流需求

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
Spring Cloud Gateway 实现API接口细粒度的限流需求

1. Spring Cloud Gateway 内置的 RequestRateLimiter 过滤器

这是最直接的实现方式:

配置示例

spring:cloud:gateway:routes:-id:users_routeuri:lb://user-servicepredicates:-Path=/api/users/**filters:-name:RequestRateLimiterargs:redis-rate-limiter.replenishRate:30# 每秒补充的令牌数redis-rate-limiter.burstCapacity:30# 令牌桶容量redis-rate-limiter.requestedTokens:1# 每次请求消耗的令牌数key-resolver:"#{@apiKeyResolver}"# 自定义Key解析器

2. 实现自定义的 KeyResolver 进行细粒度控制

@ComponentpublicclassApiKeyResolverimplementsKeyResolver{@OverridepublicMono<String>resolve(ServerWebExchangeexchange){Stringpath=exchange.getRequest().getPath().value();// 针对特定接口配置不同限流规则if(path.equals("/api/users/test1")){returnMono.just("users_test1_limit");}elseif(path.equals("/api/users/test2")){returnMono.just("users_test2_limit");}elseif(path.startsWith("/api/users")){returnMono.just("users_common_limit");}returnMono.just("default_limit");}}

3. 更灵活的多规则限流方案

3.1 使用配置中心动态管理规则

# application.ymlspring:cloud:gateway:routes:-id:dynamic_limiter_routeuri:lb://user-servicepredicates:-Path=/api/**filters:-name:RequestRateLimiterargs:key-resolver:"#{@dynamicKeyResolver}"rate-limiter:"#{@dynamicRateLimiter}"

3.2 动态限流器实现

@ComponentpublicclassDynamicRateLimiterimplementsRateLimiter{@AutowiredprivateRateLimitConfigServiceconfigService;@OverridepublicMono<Response>isAllowed(StringrouteId,Stringkey){// 从数据库或配置中心获取限流规则RateLimitRulerule=configService.getRule(key);if(rule==null){returnMono.just(newResponse(true,-1));}// 使用 Redis 或其他存储实现令牌桶算法returncheckRedisRateLimit(key,rule);}privateMono<Response>checkRedisRateLimit(Stringkey,RateLimitRulerule){// 实现基于 Redis 的令牌桶算法// ...}}

4. 基于 Sentinel 的更强大方案

4.1 集成 Sentinel

<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-sentinel</artifactId></dependency><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId></dependency>

4.2 Sentinel 配置

spring:cloud:sentinel:transport:dashboard:localhost:8080gateway:enabled:truefilter:enabled:false# 关闭默认的过滤器

4.3 定义限流规则

@ComponentpublicclassGatewayConfiguration{@PostConstructpublicvoidinitRules(){// 针对不同API设置不同规则initFlowRules();}privatevoidinitFlowRules(){List<GatewayFlowRule>rules=newArrayList<>();// /api/users 通用限流rules.add(newGatewayFlowRule("/api/users").setCount(30).setIntervalSec(60));// 特定接口限流rules.add(newGatewayFlowRule("/api/users/test1").setCount(10).setIntervalSec(60));rules.add(newGatewayFlowRule("/api/users/test2").setCount(20).setIntervalSec(60));GatewayRuleManager.loadRules(rules);}}

5. 完整的多层限流策略示例

@ConfigurationpublicclassRateLimitConfig{@Bean@PrimarypublicKeyResolverapiPathKeyResolver(){returnexchange->{Stringpath=exchange.getRequest().getPath().value();HttpMethodmethod=exchange.getRequest().getMethod();// 组合路径和方法作为KeyStringkey=method.name()+":"+path;// 支持通配符匹配if(path.matches("/api/users/test\\d+")){returnMono.just("users_specific:"+path);}returnMono.just(key);};}@BeanpublicRedisRateLimiterusersRateLimiter(){// 全局配置returnnewRedisRateLimiter(30,30);}@BeanpublicRedisRateLimitertest1RateLimiter(){// 特定接口配置returnnewRedisRateLimiter(10,10);}}

6. 结合 Kong 的分层限流架构

如果已经在使用 Kong,建议采用分层架构:

客户端 → Kong(IP级/粗粒度限流) → Spring Cloud Gateway(API级/细粒度限流) → 微服务

优势:

  1. Kong:处理全局流量控制、IP黑白名单、基础认证
  2. Spring Cloud Gateway:处理业务级限流、熔断降级、动态路由
  3. 解耦:限流规则可以在不同层级独立管理

总结

Spring Cloud Gateway 完全能够实现你描述的需求,而且有多种方案可选:

  • 简单场景:使用内置 RequestRateLimiter + 自定义 KeyResolver
  • 复杂场景:集成 Sentinel 获得更强大的流量控制能力
  • 企业级:结合配置中心实现动态规则管理

建议根据实际业务复杂度选择合适的方案。如果已经使用 Kong,可以让两个网关各司其职,实现多级防护。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/14 6:54:55

基于Java Swing的讯飞实时语音转写开发实践

前言语音识别技术在实时通信、会议记录、语音助手等场景中有着广泛应用。本文将介绍如何使用Java Swing开发一个完整的桌面级实时语音转写工具&#xff0c;集成讯飞开放平台的ASR&#xff08;自动语音识别&#xff09;服务。该工具支持麦克风实时录音和音频文件转写两种模式&am…

作者头像 李华
网站建设 2026/4/3 21:57:26

学长亲荐8个AI论文网站,助你轻松搞定本科毕业论文!

学长亲荐8个AI论文网站&#xff0c;助你轻松搞定本科毕业论文&#xff01; AI工具助你轻松应对论文难题 在本科毕业论文写作过程中&#xff0c;许多同学都面临着内容构思困难、格式不规范、重复率过高等问题。随着AI技术的不断发展&#xff0c;越来越多的AI工具开始被应用于学…

作者头像 李华
网站建设 2026/4/11 18:57:30

Java毕设项目推荐-基于SpringBoot + Vue的“校园购”二手交易平台基于SpringBoot的高校跳蚤市场交易系统【附源码+文档,调试定制服务】

博主介绍&#xff1a;✌️码农一枚 &#xff0c;专注于大学生项目实战开发、讲解和毕业&#x1f6a2;文撰写修改等。全栈领域优质创作者&#xff0c;博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java、小程序技术领域和毕业项目实战 ✌️技术范围&#xff1a;&am…

作者头像 李华
网站建设 2026/4/13 21:01:35

如何成为一名黑客?小白必学的11个基本步骤,从零基础入门到精通,看完这一篇就够了!

前言 黑客攻防是一个极具魅力的技术领域&#xff0c;但成为一名黑客毫无疑问也并不容易。你必须拥有对新技术的好奇心和积极的学习态度&#xff0c;具备很深的计算机系统、编程语言和操作系统知识&#xff0c;并乐意不断地去学习和进步。 如果你想成为一名优秀的黑客&#xf…

作者头像 李华
网站建设 2026/4/10 21:51:59

全网最全专科生AI论文平台TOP8测评

全网最全专科生AI论文平台TOP8测评 2026年专科生AI论文写作平台测评&#xff1a;为何选择这些工具&#xff1f; 随着人工智能技术的不断发展&#xff0c;越来越多的专科生开始借助AI论文写作平台来提升学习效率和论文质量。然而&#xff0c;面对市场上琳琅满目的工具&#xff0…

作者头像 李华
网站建设 2026/4/16 12:33:15

Java毕设选题推荐:基于springboot的高校二手市场交易系统基于Spring Boot+MySQL的校园二手交易系统【附源码、mysql、文档、调试+代码讲解+全bao等】

博主介绍&#xff1a;✌️码农一枚 &#xff0c;专注于大学生项目实战开发、讲解和毕业&#x1f6a2;文撰写修改等。全栈领域优质创作者&#xff0c;博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java、小程序技术领域和毕业项目实战 ✌️技术范围&#xff1a;&am…

作者头像 李华