引入redis reactive依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifatId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
resolver配置:
@Configuration
public class RequestRateLimiterConfig {
@Bean(name = "remoteAddrKeyResolver")
public KeyResolver remoteAddrKeyResolver() {
return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());
}
@Primary
@Bean(name = "apiKeyResolver")
public KeyResolver apiKeyResolver() {
return exchange -> Mono.just(exchange.getRequest().getPath().value());
}
}
yaml配置:
server:
port: 8888
spring:
cloud:
gateway:
routes:
- id: limit-route
uri: http://localhost:8080
# 重要:order越小越早捕获,比如filter设置1,Ratelimit设置0,则限流发生在filter前
order: -40
predicates:
- Path=/test/**
filters:
# 若Path配置如上,访问网关localhost:8888/test/hello,则跳转localhost:8080/hello
- StripPrefix=1
# name不可随意更改,factory中已定义
- name: RequestRateLimiter
args:
redis-rate-limiter.replenishRate: 1
redis-rate-limiter.burstCapacity: 1
key-resolver: '#{@apiKeyResolver}'
重要:如果filter中配置了order,则限流必须要配置order且数值比filter小,否则限流不生效!
上面贴出的是完整的Spring Cloud Gateway的配置,主要配置为filters
下的RequestRateLimiter
,key-resolver
表示使用名为apiKeyResolver
的限流配置配置类,此限流方式采用的是令牌桶算法的限流方式
redis-rate-limiter.replenishRate
:令牌桶每秒填充平均速率redis-rate-limiter.burstCapacity
: 令牌桶的总容量
redis中限流key: