SpringCloudGateway官方就提供了基于令牌桶的限流支持。基于其内置的过滤器工厂 RequestRateLimiterGatewayFilterFactory 实现。在过滤器工厂中是通过Redis和lua脚本结合的方式进行流量控制
简说:说白了,就是n秒内快速访问n次给你拦截住,类型网站的防cc攻击
1.在gateway(网关)加入依赖
<!--监控依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--redis的依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
2.修改application.yml配置文件,添加redis,然后启动Redis 在spring下
redis:
port: 6379
host: 127.0.0.1
3.修改application.yml配置文件,在spring-cloud-gateway-routes下 参数讲解,请看其它
filters:
- RewritePath=/api/(?<segment>.*), /$\{segment}
- name: RequestRateLimiter #限流
args:
key-resolver: '#{@pathKeyResolver}' # 使用SpEL从容器中获取对象
redis-rate-limiter.replenishRate: 1 # 令牌桶每秒填充平均速率
redis-rate-limiter.burstCapacity: 3 # 令牌桶的总容量
4.创建config包,建MyConfig类,代码如下
package com.zb.config;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Configuration
public class MyConfig {
/**
* 路径限流
*
* @return
*/
@Bean
public KeyResolver pathKeyResolver() {
return new KeyResolver() {
@Override
public Mono<String> resolve(ServerWebExchange exchange) {
return Mono.just(exchange.getRequest().getPath().toString());
}
};
}
/**
* 用户限流
* @return
*/
/* @Bean
public KeyResolver userKeyResolver() {
return new KeyResolver() {
@Override
public Mono<String> resolve(ServerWebExchange exchange) {
return Mono.just(exchange.getRequest().getQueryParams().getFirst("token"));
}
};
}*/
}
1.路径线路和用户限流只能有一个,使用一个时,另外一个必须注释掉 2.复制方法名,在application.yml粘贴方法名,即可启用/切换
key-resolver | redis-rate-limiter.replenishRate | redis-rate-limiter.burstCapacity |
---|---|---|
填写限流的方法名 | 就是几秒内 | 多少次会被拦截 |