以下是基于 Spring Cloud Alibaba Gateway 集成 Redis 限流的完整配置:
SpringCloud+全栈Java微服务+分布式,全栈开发springcloud微服务技术栈课程
配置示例
在 application.yml 或 bootstrap.yml 中添加以下配置:
yaml
spring:
redis:
host: localhost
port: 6379
password: # 如果有密码则填写
cloud:
gateway:
routes:
- id: rate_limit_route
uri: http://example.com
predicates:
- Path=/api/**
filters:
- name: RequestRateLimiter
args:
redis-rate-limiter.replenishRate: 10 # 每秒允许的请求数
redis-rate-limiter.burstCapacity: 20 # 峰值请求容量
redis-rate-limiter.requestedTokens: 1 # 每个请求消耗的令牌数
核心代码实现
SpringCloud+全栈Java微服务+分布式,全栈开发springcloud微服务技术栈课程
1. 添加依赖
确保 pom.xml 包含以下依赖:
xml
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
2. 自定义限流键解析器
创建 KeyResolver 实现类(例如基于 IP 限流):
java
@Bean
public KeyResolver ipKeyResolver() {
return exchange -> Mono.just(
exchange.getRequest().getRemoteAddress().getAddress().getHostAddress()
);
}
SpringCloud+全栈Java微服务+分布式,全栈开发springcloud微服务技术栈课程
3. 注册 KeyResolver
在配置中引用自定义的解析器:
yaml
filters:
- name: RequestRateLimiter
args:
key-resolver: "#{@ipKeyResolver}"
redis-rate-limiter.replenishRate: 10
redis-rate-limiter.burstCapacity: 20
验证限流效果
访问 /api/ 开头的接口时:
- 正常情况:每秒允许 10 个请求
- 突发流量:最高允许 20 个请求(超出后返回 HTTP 429 状态码)
SpringCloud+全栈Java微服务+分布式,全栈开发springcloud微服务技术栈课程
注意事项
- Redis 需保持可用状态
- 可通过调整
burstCapacity应对突发流量 - 自定义
KeyResolver可实现用户级/接口级等精细化限流