gateway filter

作者: 木山手札 | 来源:发表于2020-02-12 10:40 被阅读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;
        }
    }
    

    相关文章

      网友评论

        本文标题:gateway filter

        本文链接:https://www.haomeiwen.com/subject/hssqfhtx.html