GateWay具体的使用之局部过滤器接口耗时

1.找规律

局部过滤器命名规则 XXXGatewayFilterFactory, 必须以GatewayFilterFactory结尾。

复制代码
/*  注意名称约定
*   AddRequestHeaderGatewayFilterFactory    配置的时候写的是 AddRequestHeader
*   AddRequestParameterGatewayFilterFactory 配置的时候写的是 AddRequestParameter
*   LogTimeGatewayFilterFactory   配置的时候写什么? 
* */

2.接口耗时过滤器

java 复制代码
package com.by.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.cloud.gateway.filter.factory.AddRequestHeaderGatewayFilterFactory;
import org.springframework.cloud.gateway.support.GatewayToStringStyler;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class LogTimeGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {


    public GatewayFilter apply(final AbstractNameValueGatewayFilterFactory.NameValueConfig config) {
        return new GatewayFilter() {
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                String value = ServerWebExchangeUtils.expand(exchange, config.getValue());
                int times = Integer.parseInt(value);
                long start = System.currentTimeMillis();
                return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                    long end = System.currentTimeMillis();
                    long time = end - start;
                    if(time>times*1000){
                        log.info("请求耗时过长,耗时:{}",time);
                    }
                }));
            }

            public String toString() {
                return GatewayToStringStyler.filterToStringCreator(LogTimeGatewayFilterFactory.this).append(config.getName(), config.getValue()).toString();
            }
        };
    }
}

3.如何使用

相关推荐
Rysxt_1 天前
Spring Boot Gateway 教程:从入门到精通
spring boot·网关·gateway
月夕·花晨1 天前
Gateway -网关
java·服务器·分布式·后端·spring cloud·微服务·gateway
sanggou2 天前
License 集成 Spring Gateway:解决 WebFlux 非阻塞与 Spring MVC Servlet 阻塞兼容问题
spring·gateway·mvc
摘星编程8 天前
Nginx 502 Bad Gateway:从 upstream 日志到 FastCGI 超时复盘
网络·nginx·gateway·php-fpm·fastcgi
网硕互联的小客服8 天前
504 Gateway Timeout:服务器作为网关或代理时未能及时获得响应如何处理?
运维·服务器·gateway
Pierre_8 天前
通过SpringCloud Gateway实现API接口镜像请求(陪跑)网关功能
spring·spring cloud·gateway
kk在加油9 天前
智能门卫:Gateway
gateway
小安同学iter10 天前
Spring Cloud Gateway 网关(五)
java·开发语言·spring cloud·微服务·gateway
JAVA学习通10 天前
Spring Cloud ------ Gateway
java·spring cloud·gateway
weixin_4495687012 天前
访问Nginx 前端页面,接口报502 Bad Gateway
前端·nginx·gateway