添加gateway依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
创建一个LogTimeGateWayFilterFactory类,可以不是这个名字但是后面必须是xxxGateWayFilterFactory
然后继承AbstractNameValueGatewayFilterFactory
@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