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 小时前
JWT过滤器:从单体应用到微服务架构
微服务·架构·gateway·springcloud
notfound40436 小时前
解决SpringCloudGateway用户请求超时导致日志未记录情况
java·spring boot·spring·gateway·springcloud
接着奏乐接着舞1 天前
gateway
gateway
一个public的class2 天前
前后端 + Nginx + Gateway + K8s 全链路架构图解
前端·后端·nginx·kubernetes·gateway
uNke DEPH3 天前
SpringCloud Gateway 集成 Sentinel 详解 及实现动态监听Nacos规则配置实时更新流控规则
spring cloud·gateway·sentinel
ERBU DISH4 天前
当遇到 502 错误(Bad Gateway)怎么办
gateway
小超同学你好7 天前
OpenClaw 深度解析与源代码导读 · 第3篇:Gateway——常驻控制面、单端口多协议与进程骨架
人工智能·深度学习·语言模型·gateway
w6100104668 天前
Cka-2026-gateway解释
gateway·k8s·cka
岳来9 天前
网络小白docker network create时如何指定subnet 和gateway
网络·docker·gateway·subnet
如来神掌十八式10 天前
nginx + spring gateway+spring 服务_nginx 转发到 gateway
nginx·spring·gateway