1.找规律
局部过滤器命名规则 XXXGatewayFilterFactory, 必须以GatewayFilterFactory结尾。文章来源:https://www.toymoban.com/news/detail-861008.html
/* 注意名称约定
* 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();
}
};
}
}
3.如何使用
文章来源地址https://www.toymoban.com/news/detail-861008.html
到了这里,关于GateWay具体的使用之局部过滤器接口耗时的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!