1、全局filter
/**
* @author code
* @version 1.0
* @Date 2021/11/11 15:34
* @Description ${全局filter}
*/
public class TokenFilter implements GlobalFilter, Ordered {
Logger logger = LoggerFactory.getLogger(TokenFilter.class);
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain){
String token = exchange.getRequest().getQueryParams().getFirst("token");
if(token == null || token.isEmpty()){
logger.info("token is empty ...");
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
return exchange.getResponse().setComplete();
}
return chain.filter(exchange);
}
@Override
public int getOrder(){
return -100;
}
}
2、自定义filter
/**
* @author code
* @version 1.0
* @Date 2021/11/11 16:07
* @Description ${自定义过滤器}
*/
public class RequestTimeFilter implements GatewayFilter, Ordered {
Logger logger = LoggerFactory.getLogger(RequestTimeFilter.class);
private static final String REQUEST_TIME_BEGIN = "requestTimeBegin";
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain){
exchange.getAttributes().put(REQUEST_TIME_BEGIN, System.currentTimeMillis());
return chain.filter(exchange).then(
Mono.fromRunnable(() -> {
Long startTime = exchange.getAttribute(REQUEST_TIME_BEGIN);
if(startTime != null){
logger.info(exchange.getRequest().getURI().getRawPath() + ":" + (System.currentTimeMillis() - startTime) + "ms");
}
})
);
}
@Override
public int getOrder(){
return 0;
}
}
3、全局filter配置
/**
* 注册filter
*
* @return
*/
@Bean
public TokenFilter tokenFilter(){
return new TokenFilter();
}
4、自定义filter配置
@Bean
public RouteLocator routeLocator(RouteLocatorBuilder builder){
return builder.routes().
route(new Function<PredicateSpec, Route.AsyncBuilder>() {
@Override
public Route.AsyncBuilder apply(PredicateSpec predicateSpec) {
return predicateSpec
.path("/test/**")
.filters(new Function<GatewayFilterSpec, UriSpec>() {
@Override
public UriSpec apply(GatewayFilterSpec gatewayFilterSpec) {
return gatewayFilterSpec.stripPrefix(1).filter(new RequestTimeFilter());
}
})
.uri("http://ip:port")
.id("test-server");
}
}).build();
}