我们在开发系统的时候可能会对系统进行限流的需求, 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: 令牌桶的总容量