Spring Cloud Gateway根据CPU的使用情况限流

1
2
3
4
5
6
7
8
9
10
11
<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-actuator</artifactId>
</dependency>
</dependencies>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@SpringBootApplication
public class GatewayApplication {

@Autowired
private GatewayRateLimitFilterByCpu gatewayRateLimitFilterByCpu;

@Bean
public RouteLocator customerRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route(r -> r.path("/test/rateLimit")
.filters(f -> f.filter(gatewayRateLimitFilterByCpu))
.uri("http://localhost:8000/hello/rateLimit")
.id("rateLimit_route")
).build();
}
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.metrics.MetricsEndpoint;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Objects;

/**
* 根据CPU的使用情况限流
* @author yezhou
*/
@Slf4j
@Component
public class GatewayRateLimitByCpuFilter implements GatewayFilter, Ordered {

@Autowired
private MetricsEndpoint metricsEndpoint;

private static final String METRIC_NAME = "system.cpu.usage";

private static final double MAX_USAGE = 0.50D;

@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//获取网关所在机器的CPU使用情况
Double systemCpuUsage = metricsEndpoint.metric(METRIC_NAME, null)
.getMeasurements()
.stream()
.filter(Objects::nonNull)
.findFirst()
.map(MetricsEndpoint.Sample::getValue)
.filter(Double::isFinite)
.orElse(0.0D);

boolean isOpenRateLimit = systemCpuUsage > MAX_USAGE;
log.debug("system.cpu.usage: {}, isOpenRateLimit:{} ", systemCpuUsage, isOpenRateLimit);
if (isOpenRateLimit) {
//当CPU的使用超过设置的最大阀值开启限流
exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
return exchange.getResponse().setComplete();
} else {
return chain.filter(exchange);
}
}

@Override
public int getOrder() {
return 0;
}
}

Powered by AppBlog.CN     浙ICP备14037229号

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

访客数 : | 访问量 :