GateWay检查接口耗时

添加gateway依赖

java 复制代码
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

创建一个LogTimeGateWayFilterFactory类,可以不是这个名字但是后面必须是xxxGateWayFilterFactory

然后继承AbstractNameValueGatewayFilterFactory

java 复制代码
@Component
@Slf4j
public class LogTimeGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {
    @Override
    public GatewayFilter apply(NameValueConfig config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange,GatewayFilterChain chain) {
                //获取配置的超时时间
                String value = ServerWebExchangeUtils.expand(exchange, config.getValue());
                Integer timespan = Integer.valueOf(value);
                //获取开始时间
                long start = System.currentTimeMillis();
                // 往下执行完并返回后   操作.then对执行结果操作完之后在返回
                return chain.filter(exchange).then(Mono.fromRunnable(()->{
                    //获取结束时间
                    long end = System.currentTimeMillis();
                    //获取请求耗时
                    long time = end - start;
                    //判断是否超时
                    if(time > timespan*1000){
                        log.debug("请求耗时:{}ms",time);
                    }
                }));
            }

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

配置文件里配置,LogTime就是类名,但是不能带着GateWayFilterFactory

相关推荐
daladongba9 小时前
Spring Cloud Gateway
java·spring cloud·gateway
潞哥的博客3 天前
Ingress nginx退役,该怎么换,gateway api 上线
运维·gateway·k8s
Gold Steps.5 天前
K8s Gateway-API 标准化流量治理
容器·kubernetes·gateway
J_liaty5 天前
Spring Cloud Gateway与LoadBalancer深度整合实战:从基础到进阶
spring·spring cloud·gateway·loadbalancer
L***d6706 天前
SpringColoud GateWay 核心组件
gateway
悟空码字6 天前
Spring Cloud Gateway实战,从零搭建API网关,构建高性能微服务统一入口
java·gateway·springcloud·编程技术·后端开发
i***13246 天前
SpringCloud实战十三:Gateway之 Spring Cloud Gateway 动态路由
java·spring cloud·gateway
9***g6876 天前
SpringCloud Gateway 集成 Sentinel 详解 及实现动态监听Nacos规则配置实时更新流控规则
spring cloud·gateway·sentinel
lhrimperial10 天前
深入浅出Spring Cloud Gateway:从理论到企业级实践(一)
spring cloud·微服务·系统架构·gateway
lhrimperial10 天前
深入浅出Spring Cloud Gateway:从理论到企业级实践(二)
spring cloud·微服务·系统架构·gateway