news 2026/7/26 14:47:30

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/7/21 3:44:30

短语音多语种混合识别-GUI界面开发

1. 引言语音识别技术作为人工智能领域的重要分支&#xff0c;已广泛应用于智能客服、语音助手、实时字幕等多个场景。讯飞开放平台提供的大模型语音识别多语种识别服务&#xff0c;支持中文、英文、日文等多种语言&#xff0c;为开发者提供了强大的语音识别能力。本文将详细介绍…

作者头像 李华
网站建设 2026/7/14 10:57:39

【计算机毕业设计案例】基于springboot的高校二手市场交易系统基于SpringBoot + Vue的“校园购”二手交易平台(程序+文档+讲解+定制)

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

作者头像 李华
网站建设 2026/7/23 14:54:51

Spring Cloud @EnableDiscoveryClient 注解详解

一、概述 1.1 基本定义 EnableDiscoveryClient 是 Spring Cloud 中用于启用服务发现客户端功能的核心注解。它使得应用程序能够向服务注册中心注册自己&#xff0c;同时发现其他服务。 Target(ElementType.TYPE) Retention(RetentionPolicy.RUNTIME) Documented Inherited I…

作者头像 李华
网站建设 2026/7/13 21:16:14

强烈安利10个AI论文平台,自考学生轻松搞定毕业论文!

强烈安利10个AI论文平台&#xff0c;自考学生轻松搞定毕业论文&#xff01; 自考论文写作的救星&#xff0c;AI工具如何改变你的学习节奏 对于自考学生来说&#xff0c;毕业论文不仅是学业的终点&#xff0c;更是能力与毅力的考验。然而&#xff0c;面对繁重的写作任务、复杂的…

作者头像 李华