GateWay检查接口耗时

添加gateway依赖

java 复制代码
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

创建一个LogTimeGateWayFilterFactory类,可以不是这个名字但是后面必须是xxxGateWayFilterFactory

然后继承AbstractNameValueGatewayFilterFactory

java 复制代码
@Component
@Slf4j
public class LogTimeGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {
    @Override
    public GatewayFilter apply(NameValueConfig config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange,GatewayFilterChain chain) {
                //获取配置的超时时间
                String value = ServerWebExchangeUtils.expand(exchange, config.getValue());
                Integer timespan = Integer.valueOf(value);
                //获取开始时间
                long start = System.currentTimeMillis();
                // 往下执行完并返回后   操作.then对执行结果操作完之后在返回
                return chain.filter(exchange).then(Mono.fromRunnable(()->{
                    //获取结束时间
                    long end = System.currentTimeMillis();
                    //获取请求耗时
                    long time = end - start;
                    //判断是否超时
                    if(time > timespan*1000){
                        log.debug("请求耗时:{}ms",time);
                    }
                }));
            }

            @Override
            public String toString() {
                return filterToStringCreator(LogTimeGatewayFilterFactory.this)
                        .append(config.getName(), config.getValue()).toString();
            }
        };
    }
}

配置文件里配置,LogTime就是类名,但是不能带着GateWayFilterFactory

相关推荐
半旧夜夏7 小时前
【Gateway】服务调用和网关配置攻略
java·spring boot·spring cloud·gateway
小坏讲微服务11 小时前
Nginx集群与SpringCloud Gateway集成Nacos的配置指南
spring boot·nginx·spring cloud·gateway
小坏讲微服务15 小时前
使用 Spring Cloud Gateway 实现集群
java·spring boot·分布式·后端·spring cloud·中间件·gateway
没有bug.的程序员15 小时前
Spring Cloud Gateway 路由与过滤器机制
java·开发语言·spring boot·spring·gateway
serendipity_hky2 天前
【微服务 - easy视频 | day01】准备工具+gateway网关及路由至内部服务
java·微服务·架构·gateway·springcloud
三口吃掉你6 天前
微服务之网关(Spring Cloud Gateway)
java·网关·微服务·gateway
余衫马6 天前
微服务SpringCloud报错合集
spring boot·gateway
Zz_waiting.6 天前
统一服务入口-Gateway
java·开发语言·gateway
菲兹园长8 天前
微服务组件(E、L、N、O、G)
linux·服务器·gateway
tuokuac11 天前
依赖spring-cloud-starter-gateway与spring-cloud-gateway-dependencies的区别
java·gateway