基于Redis的Spring Cloud Gateway请求限流实现示例求助
基于Redis实现Spring Cloud Gateway请求限流完整示例
1. 引入依赖
如果使用Maven,在pom.xml中添加以下依赖:
<dependencies> <!-- Spring Cloud Gateway --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <!-- Redis Reactive 依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis-reactive</artifactId> </dependency> </dependencies>
如果使用Gradle:
dependencies { implementation 'org.springframework.cloud:spring-cloud-starter-gateway' implementation 'org.springframework.boot:spring-boot-starter-data-redis-reactive' }
2. 基础配置
在application.yml中配置Redis连接信息以及Gateway路由:
spring: redis: host: localhost port: 6379 # 若Redis设置密码,添加以下配置 # password: your-redis-password cloud: gateway: routes: - id: demo_route uri: http://localhost:8081 # 替换为你的后端服务地址 predicates: - Path=/api/** filters: - name: RequestRateLimiter args: redis-rate-limiter.replenishRate: 5 # 每秒允许的请求数 redis-rate-limiter.burstCapacity: 10 # 令牌桶最大容量 key-resolver: "#{@ipKeyResolver}" # 指定自定义的KeyResolver
3. 自定义KeyResolver
创建配置类,实现限流维度解析,以下是按请求IP限流的实现:
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import reactor.core.publisher.Mono; @Configuration public class RateLimiterConfig { // 按IP地址限流 @Bean public KeyResolver ipKeyResolver() { return exchange -> Mono.just( exchange.getRequest().getRemoteAddress().getAddress().getHostAddress() ); } // 可选:按请求路径限流 /* @Bean public KeyResolver pathKeyResolver() { return exchange -> Mono.just( exchange.getRequest().getPath().toString() ); } */ // 可选:按登录用户限流(需结合认证逻辑,从Header/Token中提取用户标识) /* @Bean public KeyResolver userKeyResolver() { return exchange -> Mono.just( exchange.getRequest().getHeaders().getFirst("X-User-Id") != null ? exchange.getRequest().getHeaders().getFirst("X-User-Id") : "anonymous" ); } */ }
4. 限流逻辑说明
采用RedisRateLimiter基于令牌桶算法实现限流:
replenishRate:每秒向令牌桶补充的令牌数,对应稳定请求速率burstCapacity:令牌桶最大容量,对应允许的突发请求峰值- 请求到达时,先尝试从令牌桶获取令牌,成功则放行,失败则返回
429 Too Many Requests
5. 测试验证
- 启动Redis服务,确保连接配置正确
- 启动Spring Cloud Gateway及后端服务
- 快速多次请求
http://localhost:8080/api/xxx(替换为你的路由路径),当请求频率超过阈值时,会收到429响应
内容的提问来源于stack exchange,提问作者IronMan
相关产品推荐
相关产品推荐

