springcloud

gateway filter

2020-02-12  本文已影响0人  木山手札

gateway 配置

spring:
  application:
    name: gateway-server
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true 
          lower-case-service-id: true 

GatewayFilter

public class BarFilter implements GatewayFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("BarFilter...");
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 2;
    }
}
    @Bean
    public RouteLocator barFilter(RouteLocatorBuilder builer) {
        return builer.routes()
                .route(r -> r.path("/bar-service/bar/**") // 匹配路径
                        .filters(
                                f -> f.stripPrefix(1) // 剔除bar-service
                                .filter(new BarFilter()) // 应用过滤器
                                 )
                        .uri("lb://bar-service").id("bar_filter")
                ).build();
    }

/bar-service/bar/*的路径会被添加到lb://bar-service,完整的路径是lb://bar-service/bar-service/bar/*stripPrefix(1)剔除/bar-service/bar/*中的bar-service,最后的路径是lb://bar-service/bar/*

GlobalFilter

@Component
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) {
            System.out.println("token filter fail");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        System.out.println("token filter success");
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
上一篇下一篇

猜你喜欢

热点阅读