需求:每个ip地址1秒内只能发送1次请求,多出来的请求返回429错误。
代码实现:
(1)spring cloud gateway 默认使用redis的RateLimter限流算法来实现。所以我们首先需要引入redis的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
(2)定义KeyResolver
在GatewayApplicatioin引导类中添加如下代码,KeyResolver用于计算某一个类型的限
流的KEY也就是说,可以通过KeyResolver来指定限流的Key。
**(3)修改application.yml中配置项,**指定限制流量的配置以及REDIS的配置,修改后最终配置如下:
routes:
‐ id: goods
uri: lb://goods
predicates:
‐ Path=/goods/**
filters:
‐ StripPrefix= 1
‐ name: RequestRateLimiter #请求数限流 名字不能随便写
args:
key‐resolver: "#{@ipKeyResolver}"
redis‐rate‐limiter.replenishRate: 1 #令牌桶每秒填充平均速率
redis‐rate‐limiter.burstCapacity: 1 #令牌桶总容量
(4)在启动类中 定义一个KeyResolver
@SpringBootApplication
@EnableEurekaClient
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
@Bean
public KeyResolver ipKeyResolver(){
return new KeyResolver() {
@Override
public Mono<String> resolve(ServerWebExchange exchange) {
return Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
}
};
}
}
如上配置:
表示 一秒内,允许 一个请求通过,令牌桶的填充速率也是一秒钟添加一个令牌。
最大突发状况 也只允许 一秒内有一次请求,可以根据业务来调整
(5)测试
快速刷新,当1秒内发送多次请求,就会返回429错误。