具体需求:
使用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<Void> 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
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。