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

相关推荐
亚林瓜子6 小时前
AWS API Gateway配置日志
云计算·gateway·aws·log·cloudwatch
惊鸿一博12 小时前
java_网络服务相关_gateway_nacos_feign区别联系
java·开发语言·gateway
hanniuniu131 天前
网络安全厂商F5推出AI Gateway,化解大模型应用风险
人工智能·web安全·gateway
stormsha1 天前
Proxmox Mail Gateway安装指南:从零开始配置高效邮件过滤系统
服务器·网络·网络安全·gateway
背太阳的牧羊人1 天前
backend 服务尝试连接 qdrant 容器,但失败了,返回 502 Bad Gateway 问题排查
docker·gateway·qdrant
曼彻斯特的海边2 天前
RequestRateLimiterGatewayFilterFactory
spring cloud·gateway·限流
·云扬·2 天前
【PmHub面试篇】Gateway全局过滤器统计接口调用耗时面试要点解析
面试·职场和发展·gateway
devil_mf2 天前
gateway 网关 路由新增 (已亲测)
gateway
wmd131643067122 天前
Gateway 搭建
gateway
KubeSphere 云原生4 天前
云原生周刊:探索 Gateway API v1.3.0
云原生·gateway