共计 1485 个字符,预计需要花费 4 分钟才能阅读完成。
我们在开发系统的时候可能会对系统进行限流的需求,springcloudGateway 有自带限流的方案,在此之前可以先去学习一下 springcloud gateway 中的 filter。springcloud Gateway 中提供了一个 RequestRateLimiterGatewayFilterFactory。这种限流方式用到了 redis,先添加 redis 的依赖。
配置类如下:
public class RemoteAddrKeyResolver implements KeyResolver {
public static final String BEAN_NAME = “remoteAddrKeyResolver”;
@Override
public Mono<String> resolve(ServerWebExchange exchange) {
System.out.println(“hello”);
Mono<String> just = Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());
return just;
}
}
@Configuration
public class RemoteKeyResolver {
@Bean(name=”remoteAddrKeyResolver”)
public RemoteAddrKeyResolver remoteAddrKeyResolver() {
return new RemoteAddrKeyResolver();
}
}
在此我们是根据 ip 地址限流的,Mono<String> just = Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress())
application.yml 配置文件配置如下:
spring:
application:
name: gateway-service
# redis:
# database: 0
# host: localhost
# port: 6379
# password:
# timeout: 1000ms
# lettuce:
# pool:
# max-active: 8
# max-idle: 8
# min-idle: 1
# max-wait: 1000ms
# cache:
# type: REDIS
cloud:
gateway:
discovery:
locator:
enabled: true
routes:
– id: order
uri: lb://order-service
predicates:
– Path=/api/order-service/**
filters:
– StripPrefix=1
– name: RequestRateLimiter
args:
key-resolver: ‘#{@remoteAddrKeyResolver}’
redis-rate-limiter.replenishRate: 1
redis-rate-limiter.burstCapacity: 2
上面贴出的是完整的 springcloud Gateway 的配置, 主要配置为 filters 下的 -RequestRateLimiter,key-resolver 表示使用名为 remoteAddKeyResolver 的限流配置配置类,此限流方式采用的是令牌桶算法的限流方式 redis-rate-limiter.repleushRate:令牌桶每秒填充平均速率。redis-rate-limiter.burstCapacity: 令牌桶的总容量