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级/细粒度限流) → 微服务优势:
- Kong:处理全局流量控制、IP黑白名单、基础认证
- Spring Cloud Gateway:处理业务级限流、熔断降级、动态路由
- 解耦:限流规则可以在不同层级独立管理
总结
Spring Cloud Gateway 完全能够实现你描述的需求,而且有多种方案可选:
- 简单场景:使用内置 RequestRateLimiter + 自定义 KeyResolver
- 复杂场景:集成 Sentinel 获得更强大的流量控制能力
- 企业级:结合配置中心实现动态规则管理
建议根据实际业务复杂度选择合适的方案。如果已经使用 Kong,可以让两个网关各司其职,实现多级防护。