{"id":1949,"date":"2023-04-01T10:12:32","date_gmt":"2023-04-01T02:12:32","guid":{"rendered":"https:\/\/www.appblog.cn\/?p=1949"},"modified":"2023-04-22T08:40:39","modified_gmt":"2023-04-22T00:40:39","slug":"spring-cloud-gateway-restricts-flow-based-on-cpu-usage","status":"publish","type":"post","link":"https:\/\/www.appblog.cn\/index.php\/2023\/04\/01\/spring-cloud-gateway-restricts-flow-based-on-cpu-usage\/","title":{"rendered":"Spring Cloud Gateway\u6839\u636eCPU\u7684\u4f7f\u7528\u60c5\u51b5\u9650\u6d41"},"content":{"rendered":"<pre><code class=\"language-xml\">&lt;dependencies&gt;\n    &lt;!-- Spring Cloud Gateway\u7684\u4f9d\u8d56--&gt;\n    &lt;dependency&gt;\n        &lt;groupId&gt;org.springframework.cloud&lt;\/groupId&gt;\n        &lt;artifactId&gt;spring-cloud-starter-gateway&lt;\/artifactId&gt;\n    &lt;\/dependency&gt;\n    &lt;dependency&gt;\n        &lt;groupId&gt;org.springframework.boot&lt;\/groupId&gt;\n        &lt;artifactId&gt;spring-boot-starter-actuator&lt;\/artifactId&gt;\n    &lt;\/dependency&gt;\n&lt;\/dependencies&gt;<\/code><\/pre>\n<p><!-- more --><\/p>\n<pre><code class=\"language-java\">@SpringBootApplication\npublic class GatewayApplication {\n\n    @Autowired\n    private GatewayRateLimitFilterByCpu gatewayRateLimitFilterByCpu;\n\n    @Bean\n    public RouteLocator customerRouteLocator(RouteLocatorBuilder builder) {\n        return builder.routes()\n                .route(r -&gt; r.path(&quot;\/test\/rateLimit&quot;)\n                        .filters(f -&gt; f.filter(gatewayRateLimitFilterByCpu))\n                        .uri(&quot;http:\/\/localhost:8000\/hello\/rateLimit&quot;)\n                        .id(&quot;rateLimit_route&quot;)\n                ).build();\n    }\n    public static void main(String[] args) {\n        SpringApplication.run(GatewayApplication.class, args);\n    }\n}<\/code><\/pre>\n<pre><code class=\"language-java\">import lombok.extern.slf4j.Slf4j;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.actuate.metrics.MetricsEndpoint;\nimport org.springframework.cloud.gateway.filter.GatewayFilter;\nimport org.springframework.cloud.gateway.filter.GatewayFilterChain;\nimport org.springframework.core.Ordered;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.stereotype.Component;\nimport org.springframework.web.server.ServerWebExchange;\nimport reactor.core.publisher.Mono;\n\nimport java.util.Objects;\n\n\/**\n * \u6839\u636eCPU\u7684\u4f7f\u7528\u60c5\u51b5\u9650\u6d41\n * @author yezhou\n *\/\n@Slf4j\n@Component\npublic class GatewayRateLimitByCpuFilter implements GatewayFilter, Ordered {\n\n    @Autowired\n    private MetricsEndpoint metricsEndpoint;\n\n    private static final String METRIC_NAME = &quot;system.cpu.usage&quot;;\n\n    private static final double MAX_USAGE = 0.50D;\n\n    @Override\n    public Mono&lt;Void&gt; filter(ServerWebExchange exchange, GatewayFilterChain chain) {\n        \/\/\u83b7\u53d6\u7f51\u5173\u6240\u5728\u673a\u5668\u7684CPU\u4f7f\u7528\u60c5\u51b5\n        Double systemCpuUsage = metricsEndpoint.metric(METRIC_NAME, null)\n                .getMeasurements()\n                .stream()\n                .filter(Objects::nonNull)\n                .findFirst()\n                .map(MetricsEndpoint.Sample::getValue)\n                .filter(Double::isFinite)\n                .orElse(0.0D);\n\n        boolean isOpenRateLimit = systemCpuUsage &gt; MAX_USAGE;\n        log.debug(&quot;system.cpu.usage: {}, isOpenRateLimit:{} &quot;, systemCpuUsage, isOpenRateLimit);\n        if (isOpenRateLimit) {\n            \/\/\u5f53CPU\u7684\u4f7f\u7528\u8d85\u8fc7\u8bbe\u7f6e\u7684\u6700\u5927\u9600\u503c\u5f00\u542f\u9650\u6d41\n            exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS);\n            return exchange.getResponse().setComplete();\n        } else {\n            return chain.filter(exchange);\n        }\n    }\n\n    @Override\n    public int getOrder() {\n        return 0;\n    }\n}<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>&lt;dependencies&gt; &lt;!&#8211; Spring Cloud Gateway\u7684\u4f9d\u8d56&#8211;&#038; [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[42],"tags":[439],"class_list":["post-1949","post","type-post","status-publish","format-standard","hentry","category-spring-cloud","tag-spring-cloud-gateway"],"_links":{"self":[{"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/posts\/1949","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/comments?post=1949"}],"version-history":[{"count":0,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/posts\/1949\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/media?parent=1949"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/categories?post=1949"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/tags?post=1949"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}