1.找规律
局部过滤器命名规则 XXXGatewayFilterFactory, 必须以GatewayFilterFactory结尾。
/* 注意名称约定
* AddRequestHeaderGatewayFilterFactory 配置的时候写的是 AddRequestHeader
* AddRequestParameterGatewayFilterFactory 配置的时候写的是 AddRequestParameter
* LogTimeGatewayFilterFactory 配置的时候写什么?
* */
2.接口耗时过滤器
package com.by.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.cloud.gateway.filter.factory.AddRequestHeaderGatewayFilterFactory;
import org.springframework.cloud.gateway.support.GatewayToStringStyler;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Component
@Slf4j
public class LogTimeGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {
public GatewayFilter apply(final AbstractNameValueGatewayFilterFactory.NameValueConfig config) {
return new GatewayFilter() {
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String value = ServerWebExchangeUtils.expand(exchange, config.getValue());
int times = Integer.parseInt(value);
long start = System.currentTimeMillis();
return chain.filter(exchange).then(Mono.fromRunnable(() -> {
long end = System.currentTimeMillis();
long time = end - start;
if(time>times*1000){
log.info("请求耗时过长,耗时:{}",time);
}
}));
}
public String toString() {
return GatewayToStringStyler.filterToStringCreator(LogTimeGatewayFilterFactory.this).append(config.getName(), config.getValue()).toString();
}
};
}
}