写在前面,如果项目同时存在spring-cloud-starter-gateway依赖和spring-boot-starter-web依赖,会导致过滤器等配置发送冲突导致项目启动失败。所以使用时候,要把spring-boot-starter-web依赖去掉或者禁用!!!
一、pom文件导入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
<version>3.1.6</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
二、YML文件
spring:
main:
web-application-type: reactive
#web-application-type: servlet #使用的时候,二选一
cloud:
Spring Cloud Gateway 配置项,对应 GatewayProperties 类
gateway:
discovery:
locator:
enabled: true
# 路由配置项,对应 RouteDefinition 数组
routes:
- id: rate_limiter # 唯一的路由编号
uri: localhost:8080/ # 路由到的目标地址
predicates: # 断言,作为路由的匹配条件,对应 RouteDefinition 数组
- Path=/**
# - After=2017-01-20T17:42:47.789-07:00[America/Denver]
filters:
- name: RequestRateLimiter
args:
key-resolver: "#{@ipKeyResolver}" # 获取限流 KEY 的 Bean 的名字
redis-rate-limiter.replenishRate: 100 # 令牌桶的每秒放的数量
redis-rate-limiter.burstCapacity: 500 # 令牌桶的最大令牌数
三、配置类
package scau.miniprogram.config;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
/**
* @description 限流 KEY 的 Bean ,通过解析请求的来源 IP 作为限流 KEY,这样我们就能实现基于 IP 的请求限流。
* @ClassName: GatewayConfig
* @author: zijin
* @date: 2023/7/21
* @Copyright:
*/
@Configuration
public class GatewayConfig {
@Bean
public KeyResolver ipKeyResolver() {
return new KeyResolver() {
@Override
public Mono<String> resolve(ServerWebExchange exchange) {
String host = exchange.getRequest().getRemoteAddress().getHostName();
System.out.println("!!!!!!!!");
System.err.println("IP是 "+ host);
// 获取请求的 IP
return Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
}
};
}
}