欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > 微服务--Gateway--局部过滤器接口耗时【重要】

微服务--Gateway--局部过滤器接口耗时【重要】

2024/10/23 5:45:16 来源:https://blog.csdn.net/m0_57030122/article/details/143018932  浏览:    关键词:微服务--Gateway--局部过滤器接口耗时【重要】

局部过滤器 GateWayFilter ,

通过***GateWayFilterFactory

-> 然后只需配置spring.cloud.gateway.routes[1].filters[1] = LogTime=gte,1000 【1000 单位指的是 毫秒】

1.找规律

局部过滤器命名规则 : ***GateWayFilterFactory 必须以GateWayFilterFactory结尾

/*  注意名称约定
*   AddRequestHeaderGatewayFilterFactory    配置的时候写的是 AddRequestHeader
*   AddRequestParameterGatewayFilterFactory 配置的时候写的是 AddRequestParameter
*   LogTimeGatewayFilterFactory   配置的时候 只需要配置 LogTime  即可
* */spring.cloud.gateway.routes[0].filters[0] = LogTime=gte,500

2.接口耗时过滤器

package com.***.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.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;@Slf4j
@Component
public class LogTimeGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {private static long timeSpan = 0;@Overridepublic GatewayFilter apply(NameValueConfig config) {String timeSpanStr = config.getValue();timeSpan = Long.valueOf(timeSpanStr);return new GatewayFilter() {@Overridepublic Mono<Void> filter(ServerWebExchange exchange,  GatewayFilterChain chain) {long startTime = System.currentTimeMillis();return chain.filter(exchange).then(Mono.fromRunnable(()->{long endTime = System.currentTimeMillis();// 耗时时间long time =  endTime-startTime;if(time >= timeSpan){log.debug("{} 耗时:{}",exchange.getRequest().getURI(), time);}}));}};}
}

3.使用:在配置文件中 添加配置即可

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com