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

相关推荐
Raas1005 小时前
AI网关厂商排名?MAI Gateway(魔芋企业级AI网关)vs 开源方案全面对比
人工智能·开源·gateway·ai网关·mai gateway·企业级ai网关·企业级产品
4SAPI6 小时前
企业级 RAG 知识库问答大模型 API 生产选型指南:4SAPI、硅基流动与 OpenRouter 的架构权衡
人工智能·gateway·agent·rag
JJJennie7771 天前
2026年大模型网关自建还是买?MAI Gateway等主流方案横评
人工智能·开源·gateway·ai网关
Raas1002 天前
2026年AI网关推荐?MAI Gateway(魔芋企业级AI网关)等主流方案横评
大数据·人工智能·ai·gateway·ai网关·mai gateway
4SAPI3 天前
多模型请求路由怎么设计?成本、速度和能力如何平衡
人工智能·python·gateway·php
Song_RsHt6 天前
Gateway(下):过滤器与统一鉴权
spring boot·spring·gateway
Raas1006 天前
MAI Gateway(魔芋企业级AI网关)选购攻略:AI网关哪个好?避坑指南与对比
大数据·人工智能·ai·gateway·ai网关·企业级ai网关
Song_RsHt6 天前
Gateway (上):路由与转发,微服务的统一入口
java·笔记·后端·学习·gateway