spring cloud gateway 全局過濾器

全局過濾器做用於全部的路由,不須要單獨配置,咱們能夠用它來實現不少統一化處理的業務需求,好比權限認證,IP訪問限制等等。
接口定義類:
org.springframework.cloud.gateway.filter.GlobalFilterspring

public interface GlobalFilter {
    Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain);
}

gateway自帶的GlobalFilter實現類有不少,以下圖:
spring cloud gateway 全局過濾器
GlobalFilter實現類
有轉發,路由,負載等相關的GlobalFilter,感興趣的能夠本身去看下源碼,瞭解下。
咱們本身如何定義GlobalFilter來實現咱們本身的業務邏輯?
給出一個官方文檔上的案例:json

@Configuration
public class ExampleConfiguration {
    private Logger log = LoggerFactory.getLogger(ExampleConfiguration.class);

    @Bean
    @Order(-1)
    public GlobalFilter a() {
        return (exchange, chain) -> {
            log.info("first pre filter");
            return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                log.info("third post filter");
            }));
        };
    }

    @Bean
    @Order(0)
    public GlobalFilter b() {
        return (exchange, chain) -> {
            log.info("second pre filter");
            return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                log.info("second post filter");
            }));
        };
    }

    @Bean
    @Order(1)
    public GlobalFilter c() {
        return (exchange, chain) -> {
            log.info("third pre filter");
            return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                log.info("first post filter");
            }));
        };
    }
}

上面定義了3個GlobalFilter,經過@Order來指定執行的順序,數字越小,優先級越高。下面就是輸出的日誌,從日誌就能夠看出執行的順序:markdown

2018-10-14 12:08:52.406  INFO 55062 --- [ioEventLoop-4-1] c.c.gateway.config.ExampleConfiguration  : first pre filter
2018-10-14 12:08:52.406  INFO 55062 --- [ioEventLoop-4-1] c.c.gateway.config.ExampleConfiguration  : second pre filter
2018-10-14 12:08:52.407  INFO 55062 --- [ioEventLoop-4-1] c.c.gateway.config.ExampleConfiguration  : third pre filter
2018-10-14 12:08:52.437  INFO 55062 --- [ctor-http-nio-7] c.c.gateway.config.ExampleConfiguration  : first post filter
2018-10-14 12:08:52.438  INFO 55062 --- [ctor-http-nio-7] c.c.gateway.config.ExampleConfiguration  : second post filter
2018-10-14 12:08:52.438  INFO 55062 --- [ctor-http-nio-7] c.c.gateway.config.ExampleConfiguration  : third post filter

當GlobalFilter的邏輯比較多時,我仍是推薦你們單獨寫一個GlobalFilter來處理,好比咱們要實現對IP的訪問限制,不在IP白名單中就不讓調用的需求。
單獨定義只須要實現GlobalFilter, Ordered這兩個接口就能夠了。app

@Component
public class IPCheckFilter implements GlobalFilter, Ordered {

    @Override
    public int getOrder() {
        return 0;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        HttpHeaders headers = exchange.getRequest().getHeaders();
        // 此處寫死了,演示用,實際中須要採起配置的方式
        if (getIp(headers).equals("127.0.0.1")) {
            ServerHttpResponse response = exchange.getResponse();
            ResponseData data = new ResponseData();
            data.setCode(401);
            data.setMessage("非法請求");
            byte[] datas = JsonUtils.toJson(data).getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(datas);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            return response.writeWith(Mono.just(buffer));
        }
        return chain.filter(exchange);
    }

    // 這邊從請求頭中獲取用戶的實際IP,根據Nginx轉發的請求頭獲取
    private String getIp(HttpHeaders headers) {
        return "127.0.0.1";
    }

}

過濾的使用沒什麼好講的,都比較簡單,做用卻很大,能夠處理不少需求,上面講的IP認證攔截只是冰山一角,更多的功能須要咱們本身基於過濾器去實現。
好比我想作a/b測試,那麼就得在路由轉發層面作文章,前面咱們有貼一個圖片,圖片中有不少默認的全局過濾器,其中有一個LoadBalancerClientFilter是負責選擇路由服務的負載過濾器,裏面會經過loadBalancer去選擇轉發的服務,而後傳遞到下面的路由NettyRoutingFilter過濾器去執行,那麼咱們就能夠基於這個機制來實現。
Filter中往下一個Filter中傳遞數據實用下面的方式:ide

exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, requestUrl);

獲取方直接獲取:oop

URI requestUrl = exchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);

若是我想改變路由的話,就能夠這樣作:post

@Component
public class DebugFilter implements GlobalFilter, Ordered {

    @Override
    public int getOrder() {
        return 10101;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        try {
            exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, new URI("http://192.168.31.245:8081/house/hello2"));
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return chain.filter(exchange);
    }

}

LoadBalancerClientFilter的order是10100,咱們這邊比它大1,這樣就能在它執行完以後來替換要路由的地址了。測試

相關文章推薦閱讀:ui

  •  Spring Cloud Gateway的全局異常處理
  •  AddRequestHeader GatewayFilter Factory
  •  Spring Cloud Gateway重試機制
  •  Spring Cloud Gateway 結合配置中心限流
  •  Spring Cloud Gateway 限流操做
  •  Spring Cloud Gateway 整合Eureka路由轉發
  •  Spring Cloud Gateway 網關嚐鮮日誌

    spring cloud gateway 全局過濾器

尹吉歡我不差錢啊喜歡做者

相關文章
相關標籤/搜索