一、引言
在微服务架构中,API 网关作为流量枢纽,需对进入系统的请求进行精细化限流,以保护下游服务免受流量冲击。Spring Cloud Gateway 结合 Redis 实现的令牌桶算法,为网关层限流提供了高效、分布式的解决方案。本文将深入解析其原理、配置及实践优化。
二、技术栈与原理
1. 核心组件
- Spring Cloud Gateway:作为 API 网关,提供路由、过滤等核心能力。
- Redis:作为分布式存储,实现令牌桶的状态共享,确保多网关实例的限流一致性。
- 令牌桶算法:允许突发流量(桶内令牌累积),通过固定速率生成令牌,控制请求速率,适合网关层流量整形。
2. 限流流程
- 令牌生成:Redis 每秒生成
replenishRate
个令牌,存入容量为burstCapacity
的桶中。 - 请求拦截:网关过滤器
RequestRateLimiter
检查请求对应的限流键(如用户 ID、URI)的令牌桶,有令牌则放行,无令牌则返回 429 响应。 - 分布式一致性:Redis 确保多网关实例的令牌桶状态同步,避免单机限流的局限。
三、实践步骤
1. 依赖配置
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
</dependencies>
2. Redis 连接配置(application.yml
)
spring:
redis:
host: localhost
port: 6379
database: 0
3. 定义限流维度(KeyResolver
)
import org.springframework.cloud.gateway.filter.ratelimit.<