Spring Cloud Gateway中的分布式限流

我们在开发系统的时候可能会有对系统进行限流的需求,Spring Cloud Gateway有自带限流的方案,Spring Cloud Gateway中提供了一个RequestRateLimiterGatewayFilterFactory。这种限流方式使用到了Redis, 先添加Redis的依赖:

1
2
3
4
5
6
7
8
9
10
11
12
<dependencies>
<!-- Spring Cloud Gateway的依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
</dependencies>

配置如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

public class RemoteAddrKeyResolver implements KeyResolver {

public static final String BEAN_NAME = "remoteAddrKeyResolver";

@Override
public Mono<String> resolve(ServerWebExchange exchange) {
return Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());
}

}
1
2
3
4
5
6
7
8
@Configuration
public class RemoteKeyResolver {

@Bean(name = RemoteAddrKeyResolver.BEAN_NAME)
public RemoteAddrKeyResolver remoteAddrKeyResolver() {
return new RemoteAddrKeyResolver();
}
}

在此我们是根据ip地址限流的:

1
Mono<String> just = Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());

application.yml配置文件配置如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
spring:
application:
name: ok-cloud-gateway
redis:
host: localhost
port: 6379
cloud:
gateway:
routes:
- id: rateLimit_route
uri: http://localhost:8000/hello/rateLimit
order: 0
predicates:
- Path=/test/rateLimit
filters:
#filter名称必须是RequestRateLimiter
- name: RequestRateLimiter
args:
#使用SpEL按名称引用bean
key-resolver: "#{@remoteAddrKeyResolver}"
#允许用户每秒处理多少个请求
redis-rate-limiter.replenishRate: 1
#令牌桶的容量,允许在一秒钟内完成的最大请求数
redis-rate-limiter.burstCapacity: 5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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

上面贴出的是完整的Spring Cloud Gateway的配置,主要配置为filters下的RequestRateLimiterkey-resolver表示使用名为remoteAddrKeyResolver的限流配置配置类,此限流方式采用的是令牌桶算法的限流方式

  • redis-rate-limiter.replenishRate:令牌桶每秒填充平均速率
  • redis-rate-limiter.burstCapacity: 令牌桶的总容量

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2021 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :