分布式限流:Spring Cloud Gateway 限流
在Spring Cloud Gateway中实现分布式限流,可以使用Spring Cloud Gateway内置的请求过滤器RequestRateLimiterGatewayFilterFactory
,结合Redis实现分布式限流。
- 添加依赖(pom.xml):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
- 配置application.yml:
spring:
cloud:
gateway:
routes:
- id: requestratelimiter_route
uri: http://example.com
filters:
- name: RequestRateLimiter
args:
key-resolver: '#{@ipAddressKeyResolver}'
redis-rate-limiter.replenishRate: 1 # 每秒填充平均速率
redis-rate-limiter.burstCapacity: 3 # 限流容量
redis:
host: localhost
port: 6379
- 配置限流策略的KeyResolver:
@Configuration
public class GatewayConfig {
@Bean
public KeyResolver ipAddressKeyResolver() {
return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
}
}
这样配置后,每个IP地址访问路由时都会受到限流管理,每秒只允许1个请求通过,超过限制的请求会被拦截。
注意:RequestRateLimiterGatewayFilterFactory
是依赖于Hystrix的,因此确保已经添加了spring-cloud-starter-netflix-hystrix
依赖。
评论已关闭