news 2026/4/10 17:14:23

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/7 8:36:00

一文详解Kimi的AI Agent如何跑在阿里云上

此前&#xff0c;Kimi将Agent能力落到具体产品形态中&#xff0c;在常规对话的基础上&#xff0c;相继推出了“深度研究”、Agentic PPT”、“OK Computer”及“数据分析”等多项Agent技能。 Kimi的C端Agent业务在高峰期承载了数以万计并发请求&#xff0c;每一次的请求都需要…

作者头像 李华
网站建设 2026/4/10 5:26:36

C语言内存管理:从malloc/free到柔性数组

我们之前掌握了基本的内存开辟方法&#xff1a; int val 20; char arr[10] {0};上述两种开辟有一个共同点 空间开辟大小固定数组在创建的时候&#xff0c;必须指定数组的长度&#xff0c;数组空间一旦确定了大小不能调整 但是很多情况上&#xff0c;有时候我们需要的空间大小…

作者头像 李华
网站建设 2026/4/8 1:31:55

JavaStreamAPI的性能审视,优雅语法背后的隐形成本与优化实践

在协助某电商团队进行性能问题排查时&#xff0c;我们遇到一个典型场景&#xff1a;对十万条订单数据进行处理&#xff08;筛选金额大于1000元的订单并计算平均价格&#xff09;。团队最初使用JavaStreamAPI编写的实现耗时约280毫秒&#xff0c;而一位经验丰富的同事改用传统循…

作者头像 李华
网站建设 2026/4/7 10:17:55

基于CatBoost回归模型的完整预测分析:从建模到SHAP可解释性分析

一、引言 在机器学习领域,梯度提升决策树(GBDT)算法因其强大的预测能力和鲁棒性而备受青睐。CatBoost作为俄罗斯Yandex公司开发的高性能梯度提升库,在处理类别特征和防止过拟合方面表现出色。本文将详细介绍如何使用CatBoost回归模型进行完整的预测分析流程,包括数据预处…

作者头像 李华