1.引入reactive redis maven坐标
<!--redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
<!--连接池-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
2.定义限流规则
@Configuration
public class KeyResolverConfig {
@Primary
@Bean
public KeyResolver apiKeyResolver() {
// 通过URL限流
return exchange -> Mono.just(exchange.getRequest().getURI().getPath());
}
}
3.配置限流过滤器,完成
spring:
cloud:
gateway:
routes:
- id: 用户服务
uri: lb://user-server
predicates:
- Path=/user-server/**
filters:
# 配置限流过滤器
- name: RequestRateLimiter
args:
# 指定限流规则
key-resolver: "#{@apiKeyResolver}"
# 令牌每秒生成的速度
redis-rate-limiter.replenishRate: 2
# 每秒可以请求的次数
redis-rate-limiter.burstCapacity: 2
源码位置:
?
|