1. 程式人生 > >SpringCloud Gateway 全域性過濾器

SpringCloud Gateway 全域性過濾器

全域性過濾器作用於所有的路由,不需要單獨配置,我們可以用它來實現很多統一化處理的業務需求,比如許可權認證,IP訪問限制等等。

介面定義類:org.springframework.cloud.gateway.filter.GlobalFilter

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

 

gateway自帶的GlobalFilter實現類有很多,如下圖:

GlobalFilter實現類

有轉發,路由,負載等相關的GlobalFilter,感興趣的可以自己去看下原始碼,瞭解下。

我們自己如何定義GlobalFilter來實現我們自己的業務邏輯?

給出一個官方文件上的案例:

@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來指定執行的順序,數字越小,優先順序越高。下面就是輸出的日誌,從日誌就可以看出執行的順序:

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這兩個介面就可以了。

@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中傳遞資料實用下面的方式:

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

    1

獲取方直接獲取:

URI requestUrl = exchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);

    1

如果我想改變路由的話,就可以這樣做:

@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,這樣就能在它執行完之後來替換要路由的地址了