Spring Cloud Gateway 之 過濾器

ZShUn發表於2019-02-12

Spring Cloud Gateway閘道器中有兩個過濾器,它們分別是GlobalFilter、GatewayFilter.

​ 各位朋友可能會有疑問,在zuul閘道器中只有ZuulFilter,為什麼在Spring Cloud Gateway中需要有兩個filter.其實從命名中就可以看出,GloabalFilter是全域性過濾器對於所有路由進行監控,GatewayFilter主要針對於某一個路由。那麼具體如何在Spring Cloud Gateway中使用呢?

GlobalFilter:

​ 1:實現GlobalFilter介面

@Slf4j
public class CustomGlobalFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("GlobalFilter success");
        return chain.filter(exchange);
    }
}
複製程式碼

​ 2:在配置檔案中配置bean

@Bean
public CustomGlobalFilter customGlobalFilter(){
    return new CustomGlobalFilter();
}
複製程式碼

GatewayFilter:

​ 1:繼承AbstractGatewayFilterFactory

@Slf4j
public class CustomGatewayFilter extends AbstractGatewayFilterFactory {


    @Override
    public GatewayFilter apply(Object config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                log.info("GatewayFilter success");
                return chain.filter(exchange);
            }
        };
    }
}
複製程式碼

​ 2:在yml配置檔案中指定filter

spring:
  application:
    name: gateway
  cloud:
    nacos:
      discovery:
        server-addr: 192.168.2.107:8848
      config:
        server-addr: 192.168.2.107:8848
        file-extension: yml
    gateway:
      routes:
      - id: business-account
        uri: lb://business-account
        filters:
        - CustomGatewayFilter #這裡寫類名
        predicates:
        - Path=/account/get
        - After=2017-01-20T17:42:47.789-07:00[America/Denver]
複製程式碼

​ 3:在配置檔案中配置bean

@Bean
public CustomGatewayFilter customGatewayFilter(){
    return new CustomGatewayFilter();
}
複製程式碼

​ 根據上述配置就可以正常的使用Spring Cloud Gateway過濾器了。

相關文章