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.如何使用

相关推荐
INFINI Labs21 小时前
如何使用 INFINI Gateway 对比 ES 索引数据
大数据·elasticsearch·gateway·easysearch
m0_651593912 天前
位置透明性、Spring Cloud Gateway与reactor响应式编程的关系
java·spring cloud·系统架构·gateway
nvd113 天前
使用gateway api来实现GKE 的pods 从外部访问
gateway·googlecloud
罗不俷3 天前
【Kubernetes】(二十)Gateway
容器·kubernetes·gateway
月夕·花晨5 天前
Gateway-过滤器
java·分布式·spring·spring cloud·微服务·gateway·sentinel
Ytadpole6 天前
性能革命的底层逻辑:深入理解 Spring Cloud Gateway 的 Reactor 核心
java·spring·gateway·reactor·响应式编程·cloud
柳贯一(逆流河版)8 天前
Gateway 集成 JWT 身份认证:微服务统一认证的实战指南
微服务·架构·gateway
码界奇点8 天前
Nginx 502 Bad Gateway从 upstream 日志到 FastCGI 超时深度复盘
运维·nginx·阿里云·性能优化·gateway
半夏知半秋8 天前
基于skynet框架业务中的gateway实现分析
服务器·开发语言·后端·学习·gateway
耳东哇9 天前
sentinel docker gateway k8s 集群 主从
docker·gateway·sentinel