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

相关推荐
skywalk81632 天前
LLM API Gateway:使用Comate Spec Mode创建大模型调用中转服务器
服务器·人工智能·gateway·comate
我是小妖怪,潇洒又自在2 天前
springcloud alibaba(七)Gateway--服务网关
spring·spring cloud·gateway
boy快快长大5 天前
【Spring Cloud Alibaba】Gateway(一)
数据库·gateway
谷隐凡二6 天前
网关的核心概念及简单演进介绍
gateway
摇滚侠6 天前
2025最新 SpringCloud 教程,Gateway-过滤器-基本使用,笔记58
笔记·spring cloud·gateway
摇滚侠6 天前
2025最新 SpringCloud 教程,Gateway-过滤器-globalFilter,笔记60
笔记·spring cloud·gateway
摇滚侠6 天前
2025最新 SpringCloud 教程,Gateway-过滤器-默认过滤器,笔记59
笔记·spring cloud·gateway
摇滚侠6 天前
2025最新 SpringCloud 教程,Gateway-过滤器-自定义,全局跨域,总结,笔记61,笔记62,笔记63
笔记·spring cloud·gateway
摇滚侠7 天前
2025最新 SpringCloud 教程,Gateway-断言-Query,笔记56
笔记·spring cloud·gateway