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

相关推荐
随风,奔跑2 天前
Spring Cloud Alibaba(四)---Spring Cloud Gateway
后端·spring·gateway
jiayong232 天前
Hermes Agent 的 Skills、Plugins、Gateway 深度解析
ai·gateway·agent·hermes agent·hermes
鬼蛟2 天前
Gateway
gateway
武超杰2 天前
Spring Cloud Gateway 从入门到实战
spring cloud·gateway
StackNoOverflow2 天前
Spring Cloud Gateway 服务网关详解
gateway
tsyjjOvO2 天前
服务网关 Gateway 从入门到精通
gateway
甜鲸鱼3 天前
JWT过滤器:从单体应用到微服务架构
微服务·架构·gateway·springcloud
notfound40433 天前
解决SpringCloudGateway用户请求超时导致日志未记录情况
java·spring boot·spring·gateway·springcloud
接着奏乐接着舞4 天前
gateway
gateway
一个public的class5 天前
前后端 + Nginx + Gateway + K8s 全链路架构图解
前端·后端·nginx·kubernetes·gateway