gateway(二、过滤器)
过滤器其实是路由转发+过滤器
自定义过滤器
首先创建一个类继承下边两个类,实现过滤器
然后在启动项中通过创建bean的方式创建路由器
@Component
public class TimeFilter implements GatewayFilter, Ordered {
private static final Logger logger = LoggerFactory.getLogger(TimeFilter.class);
private static final String ELAPSED_TIME_BEGIN = "timeBegin";
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
exchange.getAttributes().put(ELAPSED_TIME_BEGIN, System.currentTimeMillis());
return chain.filter(exchange).then(
Mono.fromRunnable(() -> {
Long startTime = exchange.getAttribute(ELAPSED_TIME_BEGIN);
if (startTime != null) {
logger.info(exchange.getRequest().getURI().getRawPath() + ": " + (System.currentTimeMillis() - startTime) + "ms");
}
})
);
}
@Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
}
@Bean
public RouteLocator customerRouteLocator(RouteLocatorBuilder builder) {
// @formatter:off
return builder.routes()
// .route(r -> r.path("/consulserver/**")
// .filters(f -> f.stripPrefix(1)
// .filter(new TimeFilter())
// .addResponseHeader("X-Response-Default-Foo", "Default-Bar"))
// .uri("lb://consulserver")
// .order(0)
// .id("fluent_customer_service")
// )
// .build();
}
全局过滤器只需要把继承的类改变一下就行了
之后在启动项中创建这个类的bean就行了
public class TokenFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String token = exchange.getRequest().getQueryParams().getFirst("token");
if (token == null||token.isEmpty()){
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
return exchange.getResponse().setComplete();
}
return chain.filter(exchange);
}
@Override
public int getOrder() {
return 0;
}
}在启动类中创建// @Bean
// public TokenFilter tokenFilter(){
// return new TokenFilter();
// }