10.Spring Cloud Alibaba 網(wǎng)關(guān)全局過濾

目錄:Spring Cloud Alibaba 教程
上一篇:9.Spring Cloud Alibaba 路由網(wǎng)關(guān)(Gateway)
下一篇:11. Spring Cloud Alibaba 服務(wù)配置

概述


全局過濾器作用于所有的路由,不需要單獨配置,我們可以用它來實現(xiàn)很多統(tǒng)一化處理的業(yè)務(wù)需求,比如權(quán)限認(rèn)證,IP 訪問限制等等。

注意:截止2019年06月,Spring Cloud Gateway 正式版為 2.0.2 其文檔并不完善,并且有些地方還要重新設(shè)計,這里僅提供一個基本的案例

詳見:Spring Cloud Gateway Documentation

聲明周期



Spring Cloud Gateway 基于 Project Reactor 和 WebFlux,采用響應(yīng)式編程風(fēng)格,打開它的 Filter 的接口 GlobalFilter 你會發(fā)現(xiàn)它只有一個方法 filter。

創(chuàng)建全局過濾器


實現(xiàn) GlobalFilter, Ordered 接口并在類上增加 @Component 注解就可以使用過濾功能了,非常簡單方便

package com.wsl.hello.gateway.filters;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Map;

/**
 * 鑒權(quán)過濾器
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String token = exchange.getRequest().getQueryParams().getFirst("token");

        if (token == null || token.isEmpty()) {
            ServerHttpResponse response = exchange.getResponse();

            // 封裝錯誤信息
            Map<String, Object> responseData = Maps.newHashMap();
            responseData.put("code", 401);
            responseData.put("message", "非法請求");
            responseData.put("cause", "Token is empty");

            try {
                // 將信息轉(zhuǎn)換為 JSON
                ObjectMapper objectMapper = new ObjectMapper();
                byte[] data = objectMapper.writeValueAsBytes(responseData);

                // 輸出錯誤信息到頁面
                DataBuffer buffer = response.bufferFactory().wrap(data);
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
                return response.writeWith(Mono.just(buffer));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        return chain.filter(exchange);
    }

    /**
     * 設(shè)置過濾器的執(zhí)行順序
     *
     * @return
     */
    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}
目錄結(jié)構(gòu)

測試過濾器


瀏覽器訪問:http://localhost:9000/nacos-consumer/test/app/name 網(wǎng)頁顯示

瀏覽器訪問:http://localhost:9000/nacos-consumer/test/app/name?token=123456 網(wǎng)頁顯示

Hello Nacos Discovery nacos-consumer i am from port 8082

附:Spring Cloud Gateway Benchmark


Spring 官方人員提供的網(wǎng)關(guān)基準(zhǔn)測試報告 GitHub

Proxy Avg Latency Avg Req/Sec/Thread
gateway 6.61ms 3.24k
linkered 7.62ms 2.82k
zuul 12.56ms 2.09k
none 2.09ms 11.77k
說明
  • 這里的 Zuul 為 1.x 版本,是一個基于阻塞 IO 的 API Gateway
  • Zuul 已經(jīng)發(fā)布了 Zuul 2.x,基于 Netty,非阻塞的,支持長連接,但 Spring Cloud 暫時還沒有整合計劃
  • Linkerd 基于 Scala 實現(xiàn)的、目前市面上僅有的生產(chǎn)級別的 Service Mesh(其他諸如 Istio、Conduit 暫時還不能用于生產(chǎn))。

目錄:Spring Cloud Alibaba 教程
上一篇:9.Spring Cloud Alibaba 路由網(wǎng)關(guān)(Gateway)
下一篇:11. Spring Cloud Alibaba 服務(wù)配置

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容