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

相关推荐
whz-emm6 小时前
vLLM加载lora
gateway
青衫客362 天前
Portkey-AI gateway 的一次“假压缩头”翻车的完整排障记:由 httpx 解压异常引发的根因分析
大模型·llm·gateway·httpx
PXM的算法星球7 天前
spring gateway配合nacos实现负载均衡
spring·gateway·负载均衡
1990_super7 天前
使用ceph-deploy安装和配置RADOS Gateway (RGW)并使用S3访问集群
ceph·gateway
北极糊的狐10 天前
接口返回504 Gateway Time-out 错误,这意味着请求在网关或代理服务器等待上游服务器响应时超时。以下是可能的原因和排查建议:
数据库·gateway
sg_knight11 天前
Spring Cloud Gateway全栈实践:动态路由能力与WebFlux深度整合
java·spring boot·网关·spring·spring cloud·微服务·gateway
放纵日放纵13 天前
微服务—Gateway
微服务·架构·gateway
你我约定有三14 天前
分布式微服务--GateWay(1)
java·开发语言·分布式·微服务·架构·gateway
William一直在路上17 天前
KONG API Gateway中的核心概念
网络·gateway·kong