SpringCloud網關Zuul


    近日工作中用到了SpringCloud的Zuul網關。 希望在提供網關路由轉發時,又方便額外提供一些Rest接口。

    在摸索中,有如下幾點理解:


    1:查詢Zuul的源碼,其提供一個Servlet叫:ZuulServlet,其默認處理的路徑爲:/zuul。其源碼如下。通過此可以獲知,如果一個http請求使用該

    Servlet,那麼該http請求只能是路過轉發(使用 zuul.routes 配置的地址就由ZuulServlet處理)。

    @Override
    public void service(javax.servlet.ServletRequest servletRequest, javax.servlet.ServletResponse servletResponse) throws ServletException, IOException {
        try {
            init((HttpServletRequest) servletRequest, (HttpServletResponse) servletResponse);


            // Marks this request as having passed through the "Zuul engine", as opposed to servlets
            // explicitly bound in web.xml, for which requests will not have the same data attached
            RequestContext context = RequestContext.getCurrentContext();
            context.setZuulEngineRan();


            try {
                preRoute();
            } catch (ZuulException e) {
                error(e);
                postRoute();
                return;
            }
            try {
                route();
            } catch (ZuulException e) {
                error(e);
                postRoute();
                return;
            }
            try {
                postRoute();
            } catch (ZuulException e) {
                error(e);
                return;
            }


        } catch (Throwable e) {
            error(new ZuulException(e, 500, "UNHANDLED_EXCEPTION_" + e.getClass().getName()));
        } finally {
            RequestContext.getCurrentContext().unset();
        }
    }

    

   2:Zuul提供兩個註解:@EnableZuulServer 和 @EnableZuulProxy。@EnableZuulProxy是@EnableZuulServer的增強版。其分配使用使用 ZuulServerAutoConfiguration 和ZuulProxyAutoConfiguration 分別自動注入對應的組件。 除了SpringCloud的官網介紹的差別外,還有如下差別:

        2.1:@EnableZuulServer 轉發的關鍵字是:forward.to, 可以在自定義ZuulFilter中,修改上下文RequestContext中此關鍵字對應的值來改變路由路徑。

        2.2:@EnableZuulServer 是使用 RequestDispatcher 類進行轉發,那麼其無法訪問SpringCloud的SerivceID 和 自動進行負載均衡。

        2.3:@EnableZuulProxy 默認使用的是RestClient進行路由,可以訪問SpringCloud的SerivceID 和 自動進行負載均衡。其路由關鍵字是: serviceId    


 3:關於 ZuulFilter。

     3.1:自定義ZuulFilter的 filterOrder 函數返回值很重要,其決定了在同類型的Filter中,執行的順序,值越小的越先執行。

     3.2:函數 shouldFilter() 爲false的Filter則不會被執行。

     3.3: run() 方法的返回值沒什麼用處。 此方法類如果拋出異常,則同類型的其餘爲執行的Filter則不會再執行







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章