Spring Cloud Gateway打印请求的执行时间

具体需求:

使用spring cloud gateway作为网关,打印每个请求的执行时长

具体实现:

自定义GlobalFilter,当请求进入时记录开始时间,当请求结束时,减去开始时间即为具体的执行时长
package com.winture.gateway.filter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 打印请求参数及统计执行时长过滤器
 * @Version V1.0
 */
@Component
public class LoggingFilter implements GlobalFilter, Ordered {

    private static final Log logger = LogFactory.getLog(LoggingFilter.class);
    private static final String START_TIME = "startTime";

    public LoggingFilter() {
        logger.info("Loaded GlobalFilter [Logging]");
    }

    @Override
    public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String info = String.format("Method:{%s} Host:{%s} Path:{%s} Query:{%s}",
                exchange.getRequest().getMethod().name(),
                exchange.getRequest().getURI().getHost(),
                exchange.getRequest().getURI().getPath(),
                exchange.getRequest().getQueryParams());

        logger.info(info);

        exchange.getAttributes().put(START_TIME, System.currentTimeMillis());
        return chain.filter(exchange).then( Mono.fromRunnable(() -> {
            Long startTime = exchange.getAttribute(START_TIME);
            if (startTime != null) {
                Long executeTime = (System.currentTimeMillis() - startTime);
                logger.info(exchange.getRequest().getURI().getRawPath() + " : " + executeTime + "ms");
            }
        }));
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}

当网关启动后,访问网关,可以看到如下的打印信息

2018-08-31 18:35:02.644  INFO 14376 --- [ctor-http-nio-2] c.w.gateway.filter.LoggingFilter       : Method:{POST} Host:{127.0.0.1} Path:{/api/authorize} Query:{{}}
2018-08-31 18:35:02.678  INFO 14376 --- [ctor-http-nio-3] c.w.gateway.filter.LoggingFilter       : /api/authorize : 34ms

你可能感兴趣的:(Spring Cloud Gateway打印请求的执行时间)