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

相关推荐
lhrimperial2 天前
深入浅出Spring Cloud Gateway:从理论到企业级实践(一)
spring cloud·微服务·系统架构·gateway
lhrimperial2 天前
深入浅出Spring Cloud Gateway:从理论到企业级实践(二)
spring cloud·微服务·系统架构·gateway
ghostwritten3 天前
云原生流量治理新标准:Kubernetes Gateway API 部署实践指南
云原生·kubernetes·gateway
齐 飞3 天前
Spring Cloud Alibaba快速入门-Gateway
spring cloud·微服务·gateway
Linux运维技术栈3 天前
Gravitee Kafka Gateway 规范部署:HTTP API化封装与安全隔离实践
http·kafka·gateway
trayvontang5 天前
Spring Gateway核心概念、流程及原理
spring·gateway·spring gateway
trayvontang5 天前
Spring Gateway常用过滤器(限流、熔断等)
spring·gateway·spring gateway·gateway常用过滤器
Hello.Reader7 天前
Flink SQL Gateway 把 Flink SQL 变成“多客户端并发可用”的统一服务入口
sql·flink·gateway
ygqygq28 天前
Kubernetes Gateway API 与 Envoy Gateway 部署使用指南
kubernetes·gateway·envoy·ingress
weixin_439706259 天前
spring boot+nacos+gateway+sentinel的简单例子
spring boot·gateway·sentinel