SpringCloud-源码分析 zuul (一)

本文作者:陈刚,叩丁狼高级讲师。原创文章,转载请注明出处。

zuul舍命周期

zuul,在SpringCloud中充当服务网关的角色,它包含了请求路由,过滤,安全等功能,可以说是我们web应用的“安保人员”,保证了我们“微服务园区”的安全,那么zuul是如何实现路由和过滤等功能的呢?我这里有一张摘抄于SpringCloud官网的zuul的生命周期图片

 

SpringCloud-源码分析 zuul (一)_第1张图片

叩丁狼教育.png

 

这张图的大致流程为:
1.当客户端请求过来首先会到 "pre" filters 这样的一个前置过滤器做一些处理,然后调用自定义的过滤器
2.前置过滤器执行完了之后会调用 “routing”filter 过滤器 ,看名字都知道这是做路由分发的过滤器
3.在路由的过程中出现了异常,那么会走 “error”filters过滤器,然后再走 "post"filters 过滤器 ,或者正常路由完成也会走到“post”filters
4."post"filters过滤器负责处理响应 ,最后把结果响应给客户端

这里是zuul大致的生命周期流程,我们看到它这里大量用到了filter进行处理,并且Zuul允许我们自定义Filter ,他提供了抽象的 ZuulFilter 过滤器,里面有四个基本方法,我们要自定义Filter就需要继承ZuulFilter,然后复写四个方法

/**
 服务过滤
 */
@Component
public class MyFilter extends ZuulFilter {


    /**
        返回过滤器的类型,过滤器类型如下:
        pre:请求路由之前调用过滤
        routing:请求routing之时调用过滤
        post: 请求路由之后调用过滤
        error:发送错误时调用过滤
     */
    @Override
    public String filterType() {
        return "pre";
    }

    //filterOrder:过滤的顺序
    @Override
    public int filterOrder() {
        return 0;
    }

    //shouldFilter:是否要过滤,true表示永远过滤。我们可以在这里做一写过滤处理
    @Override
    public boolean shouldFilter() {
        return true;
    }

 
  //当前过滤器的执行方法
  //我们可以在该方法中处理一些自己的判断
    @Override
    public Object run() {
        //获取请求对象
        RequestContext ctx = RequestContext.getCurrentContext();
        Object pass = ctx.getRequest().getParameter("pass");
        if(pass == null) {
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            try {
                ctx.getResponse().getWriter().write("pass is empty");
            }catch (Exception e){}
        }
        return null;
    }
}

那么我们接下来就分析他的源码就是去看这些内置的filter做了什么事情。

zuul的启动/配置

简单回顾一下zuul的使用 ,除了引入zuul相关依赖而外,我们要使用zull还需要在配置类上开启zuul功能

//@EnableZuulProxy :开启路由网关功能
@SpringBootApplication
@EnableZuulProxy
public class ServiceZuulApplication {

    public static void main(String[] args) {
        SpringApplication.run(ServiceZuulApplication.class, args);
    }
}

EnableZuulProxy的注释告诉我们,这里设设置Zuul服务器端点,和安装了一些过滤器,通过这些过滤器它可以转发请求到后端服务器

/**
 * Sets up a Zuul server endpoint and installs some reverse proxy filters in it, so it can
 * forward requests to backend servers. The backends can be registered manually through
 * configuration or via DiscoveryClient.
 *
 * @see EnableZuulServer for how to get a Zuul server without any proxying
 *
 * @author Spencer Gibb
 * @author Dave Syer
 * @author Biju Kunjummen
 */
@EnableCircuitBreaker
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(ZuulProxyMarkerConfiguration.class)
public @interface EnableZuulProxy {
}

不过这里引入了 ZuulProxyMarkerConfiguration 配置类,这个配置在干嘛呢?

/**
 * Responsible for adding in a marker bean to trigger activation of 
 * {@link ZuulProxyAutoConfiguration}
 *
 * @author Biju Kunjummen
 */

@Configuration
public class ZuulProxyMarkerConfiguration {
    @Bean
    public Marker zuulProxyMarkerBean() {
        return new Marker();
    }

    class Marker {
    }
}

翻译:“Responsible for adding in a marker bean to trigger activation of

  • {@link ZuulProxyAutoConfiguration}”
    它在负责添加标记bean以触发激活 ZuulProxyAutoConfiguration 这个类,研究过springboot自动配置的同学就会知道 ,SpringBoot 中会有大量的 xxxAutoConfiguration 自动配置的类会在应用启动的过程中被激活实现自动装配,从而节省了我们很多的配置。

而这个类在配置些什么东西?

/**
 * @author Spencer Gibb
 * @author Dave Syer
 * @author Biju Kunjummen
 */
@Configuration
//这里引入了几种客户端配置
@Import({ RibbonCommandFactoryConfiguration.RestClientRibbonConfiguration.class,
        RibbonCommandFactoryConfiguration.OkHttpRibbonConfiguration.class,
        RibbonCommandFactoryConfiguration.HttpClientRibbonConfiguration.class,
        HttpClientConfiguration.class })
//如果存在了 ZuulProxyMarkerConfiguration.Marker的实例,该配置生效,这里是满足条件的
@ConditionalOnBean(ZuulProxyMarkerConfiguration.Marker.class)
public class ZuulProxyAutoConfiguration extends ZuulServerAutoConfiguration {
...省略代码...

ZuulProxyAutoConfiguration继承了 ZuulServerAutoConfiguration ,我们先看下这个配置类


/**
 * @author Spencer Gibb
 * @author Dave Syer
 * @author Biju Kunjummen
 */
@Configuration
@EnableConfigurationProperties({ ZuulProperties.class })
@ConditionalOnClass(ZuulServlet.class)
@ConditionalOnBean(ZuulServerMarkerConfiguration.Marker.class)
// Make sure to get the ServerProperties from the same place as a normal web app would
// FIXME @Import(ServerPropertiesAutoConfiguration.class)
public class ZuulServerAutoConfiguration {
  //绑定zuul的配置信息
    @Autowired
    protected ZuulProperties zuulProperties;

    @Autowired
    protected ServerProperties server;

//注入请求错误控制器
    @Autowired(required = false)
    private ErrorController errorController;

    @Bean
    public HasFeatures zuulFeature() {
        return HasFeatures.namedFeature("Zuul (Simple)", ZuulServerAutoConfiguration.class);
    }

//RouteLocator that composes multiple RouteLocators. :
//多路由组合定位器
    @Bean
    @Primary
    public CompositeRouteLocator primaryRouteLocator(
            Collection routeLocators) {
        return new CompositeRouteLocator(routeLocators);
    }

//简单的路由定位器
    @Bean
    @ConditionalOnMissingBean(SimpleRouteLocator.class)
    public SimpleRouteLocator simpleRouteLocator() {
        return new SimpleRouteLocator(this.server.getServlet().getServletPrefix(),
                this.zuulProperties);
    }


    @Bean
    public ZuulController zuulController() {
        return new ZuulController();
    }

// MVC HandlerMapping that maps incoming request paths to remote services.
//看名字也知道,他是做请求路径和远程服务的映射的,是  HandlerMapping的实现
    @Bean
    public ZuulHandlerMapping zuulHandlerMapping(RouteLocator routes) {
        ZuulHandlerMapping mapping = new ZuulHandlerMapping(routes, zuulController());
        mapping.setErrorController(this.errorController);
        return mapping;
    }

//定义ZuulRefreshListener  zuul刷新的监听器
    @Bean
    public ApplicationListener zuulRefreshRoutesListener() {
        return new ZuulRefreshListener();
    }

// Core Zuul servlet which intializes and orchestrates zuulFilter execution
//这里在注册ZuulServlet 这样的一个servlet, 这个东西了不得了,
//他是负责核心Zuul servlet初始化和调用zuulFilter执行,跟DispatcherServlet差不过
    @Bean
    @ConditionalOnMissingBean(name = "zuulServlet")
    public ServletRegistrationBean zuulServlet() {
        ServletRegistrationBean servlet = new ServletRegistrationBean<>(new ZuulServlet(),
                this.zuulProperties.getServletPattern());
        // The whole point of exposing this servlet is to provide a route that doesn't
        // buffer requests.
        servlet.addInitParameter("buffer-requests", "false");
        return servlet;
    }

    // pre filters  : 
//前置过滤器,看名字是用来做检测的
    @Bean
    public ServletDetectionFilter servletDetectionFilter() {
        return new ServletDetectionFilter();
    }
//前置过滤器,是对请求数据做一些增强处理
    @Bean
    public FormBodyWrapperFilter formBodyWrapperFilter() {
        return new FormBodyWrapperFilter();
    }


    @Bean
    public DebugFilter debugFilter() {
        return new DebugFilter();
    }

    @Bean
    public Servlet30WrapperFilter servlet30WrapperFilter() {
        return new Servlet30WrapperFilter();
    }

    // post filters
       //下面是定义一系列的后置过滤器
    @Bean
    public SendResponseFilter sendResponseFilter(ZuulProperties properties) {
        return new SendResponseFilter(zuulProperties);
    }

    @Bean
    public SendErrorFilter sendErrorFilter() {
        return new SendErrorFilter();
    }

    @Bean
    public SendForwardFilter sendForwardFilter() {
        return new SendForwardFilter();
    }           

整理一下这里配置类里面做了哪些事情呢?
1.注册了多路由组合定位器 CompositeRouteLocator
2.注册了简单的路由定位器SimpleRouteLocator
3.注册了ZuulController ,zuulServlet会通过调用它再,实现对请求的调用他的源码如下

**
 * @author Spencer Gibb
 */
public class ZuulController extends ServletWrappingController {

    public ZuulController() {
        setServletClass(ZuulServlet.class);
        setServletName("zuul");
        setSupportedMethods((String[]) null); // Allow all
    }

    @Override
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            // We don't care about the other features of the base class, just want to
            // handle the request
//处理请求
            return super.handleRequestInternal(request, response);
        }
        finally {
            // @see com.netflix.zuul.context.ContextLifecycleFilter.doFilter
            RequestContext.getCurrentContext().unset();
        }
    }

}

4.注册了ZuulHandlerMapping 是对path和远程服务的映射

  1. 注册了zuulServlet : 请求的分发器类似于DispatcherServlet

6.定义了一系列的前置过滤器和后置过滤器,作用分别如下:

ServletDetectionFilter : 标记处理servlet的类型,前置通知 ,执行顺序 -3

/**
 * Detects whether a request is ran through the {@link DispatcherServlet} or {@link ZuulServlet}.
 * The purpose was to detect this up-front at the very beginning of Zuul filter processing
 *  and rely on this information in all filters.
 *  RequestContext is used such that the information is accessible to classes 
 *  which do not have a request reference.
 * @author Adrian Ivan
 */
public class ServletDetectionFilter extends ZuulFilter {

    public ServletDetectionFilter() {
    }
//前置通知
    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    /**
     * Must run before other filters that rely on the difference between 
     * DispatcherServlet and ZuulServlet.
     */
//filterOrder 决定了这个过滤器的执行顺序 这里是 :-3 见
//public static final int SERVLET_DETECTION_FILTER_ORDER = -3;
    @Override
    public int filterOrder() {
        return SERVLET_DETECTION_FILTER_ORDER;
    }

    @Override
    public boolean shouldFilter() {
        return true; 
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
//判断结果保存到  HttpServletRequest中
        HttpServletRequest request = ctx.getRequest();
        if (!(request instanceof HttpServletRequestWrapper) 
                && isDispatcherServletRequest(request)) {
            ctx.set(IS_DISPATCHER_SERVLET_REQUEST_KEY, true);
        } else {
            ctx.set(IS_DISPATCHER_SERVLET_REQUEST_KEY, false);
        }

        return null;
    }
    
//判断当前请求是否是DispatcherServletRequest
    private boolean isDispatcherServletRequest(HttpServletRequest request) {
        return request.getAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null;
    }       

翻译过滤器上面的注释"Detects whether a request is ran through the {@link DispatcherServlet} or {@link ZuulServlet}"大致功能为:用来标记该请求是通过 DispatcherServlet处理还是通过 ZuulServlet处理
,run()把判断结果以boolean值的方式保存到HttpServletRequest中,后续的处理中就可以通过它获取到这个标记做不同的处理,而这个filter执行的顺序是 -3(filterOrder() 方法) ,越小越先执行


FormBodyWrapperFilter :解析表单数据并为后续处理重新编码,将符合要求的请求体包装成FormBodyRequestWrapper对象。前置通知,执行顺序 -1

/**
 * Pre {@link ZuulFilter} that parses form data and reencodes it for downstream services
 *
 * @author Dave Syer
 */
public class FormBodyWrapperFilter extends ZuulFilter {
...省略...
@Override
    public String filterType() {
//前置通知
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
//执行顺序 -1
        return FORM_BODY_WRAPPER_FILTER_ORDER;
    }
@Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
//处理请求
        HttpServletRequest request = ctx.getRequest();
        FormBodyRequestWrapper wrapper = null;
        if (request instanceof HttpServletRequestWrapper) {
            HttpServletRequest wrapped = (HttpServletRequest) ReflectionUtils
                    .getField(this.requestField, request);
            wrapper = new FormBodyRequestWrapper(wrapped);
            ReflectionUtils.setField(this.requestField, request, wrapper);
            if (request instanceof ServletRequestWrapper) {
                ReflectionUtils.setField(this.servletRequestField, request, wrapper);
            }
        }
        else {
//包装成 FormBodyRequestWrapper
            wrapper = new FormBodyRequestWrapper(request);
            ctx.setRequest(wrapper);
        }
        if (wrapper != null) {
            ctx.getZuulRequestHeaders().put("content-type", wrapper.getContentType());
        }
        return null;
    }
...省略...

DebugFilter :开启调试标记 ,前置通知 ,执行顺序 1

/**
 * Pre {@link ZuulFilter} that sets {@link RequestContext} debug attributes to true if
 * the "debug" request parameter is set.
 *
 * @author Spencer Gibb
 */
public class DebugFilter extends ZuulFilter {

    private static final DynamicBooleanProperty ROUTING_DEBUG = DynamicPropertyFactory
            .getInstance().getBooleanProperty(ZuulConstants.ZUUL_DEBUG_REQUEST, false);

    private static final DynamicStringProperty DEBUG_PARAMETER = DynamicPropertyFactory
            .getInstance().getStringProperty(ZuulConstants.ZUUL_DEBUG_PARAMETER, "debug");

    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return DEBUG_FILTER_ORDER;
    }

    @Override
    public boolean shouldFilter() {
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        if ("true".equals(request.getParameter(DEBUG_PARAMETER.get()))) {
            return true;
        }
        return ROUTING_DEBUG.get();
    }

翻译注释“Pre {@link ZuulFilter} that sets {@link RequestContext} debug attributes to true if the "debug" request parameter is set.”
如果请求中设置了“debug”请求参数, RequestContext调试属性设置为true。说白了就是通过 reques中的debug参数来激活调试信息,这样当线上环境出现问题的时候,可以通过请求参数的方式来激活这些debug信息以帮助分析问题


Servlet30WrapperFilter :包装http请求 ,前置通知 ,执行顺序 -2


/**
 * Pre {@link ZuulFilter} that wraps requests in a Servlet 3.0 compliant wrapper.
 * Zuul's default wrapper is only Servlet 2.5 compliant.
 * @author Spencer Gibb
 */
public class Servlet30WrapperFilter extends ZuulFilter {

    private Field requestField = null;

    public Servlet30WrapperFilter() {
        this.requestField = ReflectionUtils.findField(HttpServletRequestWrapper.class,
                "req", HttpServletRequest.class);
        Assert.notNull(this.requestField,
                "HttpServletRequestWrapper.req field not found");
        this.requestField.setAccessible(true);
    }

    protected Field getRequestField() {
        return this.requestField;
    }

    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return SERVLET_30_WRAPPER_FILTER_ORDER;
    }
@Override
    public Object run() {
//把请求包装成  Servlet30RequestWrapper
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        if (request instanceof HttpServletRequestWrapper) {
            request = (HttpServletRequest) ReflectionUtils.getField(this.requestField,
                    request);
            ctx.setRequest(new Servlet30RequestWrapper(request));
        }
        else if (RequestUtils.isDispatcherServletRequest()) {
            // If it's going through the dispatcher we need to buffer the body

            ctx.setRequest(new Servlet30RequestWrapper(request));
        }
        return null;
    }

翻译注释:“that wraps requests in a Servlet 3.0 compliant wrapper.
Zuul's default wrapper is only Servlet 2.5 compliant.”
这里是对原始的HttpServletRequest请求包装成Servlet30RequestWrapper对象即要兼容3.0。zuul默认只是兼容2.5,你现在知道为什么他叫 Servlet30WrapperFilter 了吗?


SendResponseFilter :后置通知 ,处理请求响应,执行顺序 1000

/**
 * Post {@link ZuulFilter} that writes responses from proxied requests to the current response.
 *
 * @author Spencer Gibb
 * @author Dave Syer
 * @author Ryan Baxter
 */
public class SendResponseFilter extends ZuulFilter {
...省略...

@Override
    public Object run() {
        try {
            addResponseHeaders();
            writeResponse();
        }
        catch (Exception ex) {
            ReflectionUtils.rethrowRuntimeException(ex);
        }
        return null;
    }


private void writeResponse() throws Exception {
        RequestContext context = RequestContext.getCurrentContext();
        // there is no body to send
        if (context.getResponseBody() == null
                && context.getResponseDataStream() == null) {
            return;
        }
        HttpServletResponse servletResponse = context.getResponse();
        if (servletResponse.getCharacterEncoding() == null) { // only set if not set
            servletResponse.setCharacterEncoding("UTF-8");
        }
        OutputStream outStream = servletResponse.getOutputStream();
        InputStream is = null;
        try {
            if (RequestContext.getCurrentContext().getResponseBody() != null) {
                String body = RequestContext.getCurrentContext().getResponseBody();
                writeResponse(
                        new ByteArrayInputStream(
                                body.getBytes(servletResponse.getCharacterEncoding())),
                        outStream);
                return;
            }
...省略...


//写响应结果
private void writeResponse(InputStream zin, OutputStream out) throws Exception {
        byte[] bytes = buffers.get();
        int bytesRead = -1;
        while ((bytesRead = zin.read(bytes)) != -1) {
            out.write(bytes, 0, bytesRead);
        }
    }

翻译:that writes responses from proxied requests to the current response.
翻译大致意思为把代理请求的响应写入到当前响应,
String body = RequestContext.getCurrentContext().getResponseBody(); 获取到响应内容 ,通过 servletResponse.getOutputStream(); 写出去 ,
我们从源码中可以看到该过滤器会检查请求上下文中是否包含请求响应相关的头信息、响应数据流或是响应体,然后利用请求上下文的响应信息来组织需要发送回客户端的响应内容。


SendErrorFilter :错误处理过滤器 ,把错误重定向到/error路径上,执行顺序 0


/**
 * Error {@link ZuulFilter} that forwards to /error (by default) if {@link RequestContext#getThrowable()} is not null.
 *
 * @author Spencer Gibb
 */
//TODO: move to error package in Edgware
public class SendErrorFilter extends ZuulFilter {

    private static final Log log = LogFactory.getLog(SendErrorFilter.class);
    protected static final String SEND_ERROR_FILTER_RAN = "sendErrorFilter.ran";

//异常重定向路径
    @Value("${error.path:/error}")
    private String errorPath;

    @Override
    public String filterType() {
        return ERROR_TYPE;
    }

    @Override
    public int filterOrder() {
        return SEND_ERROR_FILTER_ORDER;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        // only forward to errorPath if it hasn't been forwarded to already
        return ctx.getThrowable() != null
                && !ctx.getBoolean(SEND_ERROR_FILTER_RAN, false);
    }

    @Override
    public Object run() {
        try {
            RequestContext ctx = RequestContext.getCurrentContext();
//找到异常
            ZuulException exception = findZuulException(ctx.getThrowable());
            HttpServletRequest request = ctx.getRequest();

//处理异常错误码等
            request.setAttribute("javax.servlet.error.status_code", exception.nStatusCode);

            log.warn("Error during filtering", exception);
            request.setAttribute("javax.servlet.error.exception", exception);

            if (StringUtils.hasText(exception.errorCause)) {
                request.setAttribute("javax.servlet.error.message", exception.errorCause);
            }

            RequestDispatcher dispatcher = request.getRequestDispatcher(
                    this.errorPath);
            if (dispatcher != null) {
                ctx.set(SEND_ERROR_FILTER_RAN, true);
                if (!ctx.getResponse().isCommitted()) {
                    ctx.setResponseStatusCode(exception.nStatusCode);
                    dispatcher.forward(request, ctx.getResponse());
                }
            }
        }
        catch (Exception ex) {
            ReflectionUtils.rethrowRuntimeException(ex);
        }
        return null;
    }

SendForwardFilter:用来处理路由规则中的forward本地跳转配置 ,执行顺序 5000

/**
 * Route {@link ZuulFilter} that forwards requests using the {@link RequestDispatcher}.
 * Forwarding location is located in the {@link RequestContext} attribute {@link org.springframework.cloud.netflix.zuul.filters.support.FilterConstants#FORWARD_TO_KEY}.
 * Useful for forwarding to endpoints in the current application.
 用户RequestDispatcher 进行本地应用端点的Forwarding
 * @author Dave Syer
 */
public class SendForwardFilter extends ZuulFilter {
...省略...
    @Override
    public Object run() {
        try {
            RequestContext ctx = RequestContext.getCurrentContext();
            String path = (String) ctx.get(FORWARD_TO_KEY);
            RequestDispatcher dispatcher = ctx.getRequest().getRequestDispatcher(path);
            if (dispatcher != null) {
                ctx.set(SEND_FORWARD_FILTER_RAN, true);
                if (!ctx.getResponse().isCommitted()) {
//请求跳转
                    dispatcher.forward(ctx.getRequest(), ctx.getResponse());
                    ctx.getResponse().flushBuffer();
                }
            }
        }
        catch (Exception ex) {
            ReflectionUtils.rethrowRuntimeException(ex);
        }
        return null;
    }

你以为到这里就完了吗,并没有,我们刚才看的是ZuulServerAutoConfiguration中定义的过滤器,在ZuulProxyAutoConfiguration中还定义了一些过滤器

/**
 * @author Spencer Gibb
 * @author Dave Syer
 * @author Biju Kunjummen
 */
@Configuration
@Import({ RibbonCommandFactoryConfiguration.RestClientRibbonConfiguration.class,
        RibbonCommandFactoryConfiguration.OkHttpRibbonConfiguration.class,
        RibbonCommandFactoryConfiguration.HttpClientRibbonConfiguration.class,
        HttpClientConfiguration.class })
@ConditionalOnBean(ZuulProxyMarkerConfiguration.Marker.class)
public class ZuulProxyAutoConfiguration extends ZuulServerAutoConfiguration {
...省略代码...
// pre filters  : 前置过滤
    @Bean
    public PreDecorationFilter preDecorationFilter(RouteLocator routeLocator, ProxyRequestHelper proxyRequestHelper) {
        return new PreDecorationFilter(routeLocator, this.server.getServlet().getServletPrefix(), this.zuulProperties,
                proxyRequestHelper);
    }

    // route filters   :路由过滤
    @Bean
    public RibbonRoutingFilter ribbonRoutingFilter(ProxyRequestHelper helper,
            RibbonCommandFactory ribbonCommandFactory) {
        RibbonRoutingFilter filter = new RibbonRoutingFilter(helper, ribbonCommandFactory,
                this.requestCustomizers);
        return filter;
    }

    @Bean
    @ConditionalOnMissingBean({SimpleHostRoutingFilter.class, CloseableHttpClient.class})
    public SimpleHostRoutingFilter simpleHostRoutingFilter(ProxyRequestHelper helper,
            ZuulProperties zuulProperties,
            ApacheHttpClientConnectionManagerFactory connectionManagerFactory,
            ApacheHttpClientFactory httpClientFactory) {
        return new SimpleHostRoutingFilter(helper, zuulProperties,
                connectionManagerFactory, httpClientFactory);
    }

    @Bean
    @ConditionalOnMissingBean({SimpleHostRoutingFilter.class})
    public SimpleHostRoutingFilter simpleHostRoutingFilter2(ProxyRequestHelper helper,
                                                           ZuulProperties zuulProperties,
                                                           CloseableHttpClient httpClient) {
        return new SimpleHostRoutingFilter(helper, zuulProperties,
                httpClient);
    }


PreDecorationFilter :匹配路由过着和服务位置、在请求上下文中设置该请求的基本信息 ,执行顺序 5

/**
 * Pre {@link ZuulFilter} that determines where and how to route based on the supplied {@link RouteLocator}.
 * Also sets various proxy related headers for downstream requests.
 */
public class PreDecorationFilter extends ZuulFilter {
...省略...
@Override
    public Object run() {
//请求上下文
        RequestContext ctx = RequestContext.getCurrentContext();
//请求路径
        final String requestURI = this.urlPathHelper.getPathWithinApplication(ctx.getRequest());
//根据请求地址,匹配匹配路由
        Route route = 
this.routeLocator.getMatchingRoute(requestURI);
        if (route != null) {
//从路由中获取请求服务id
            String location = route.getLocation();
            if (location != null) {
//设置请求上下文相关信息
                ctx.put(REQUEST_URI_KEY, route.getPath());
                ctx.put(PROXY_KEY, route.getId());
                if (!route.isCustomSensitiveHeaders()) {
                    this.proxyRequestHelper
                            .addIgnoredHeaders(this.properties.getSensitiveHeaders().toArray(new String[0]));
                }
                else {
                    this.proxyRequestHelper.addIgnoredHeaders(route.getSensitiveHeaders().toArray(new String[0]));
                }
if (route.getRetryable() != null) {
                    ctx.put(RETRYABLE_KEY, route.getRetryable());
                }

                if (location.startsWith(HTTP_SCHEME+":") || location.startsWith(HTTPS_SCHEME+":")) {
                    ctx.setRouteHost(getUrl(location));
                    ctx.addOriginResponseHeader(SERVICE_HEADER, location);
                }
                else if (location.startsWith(FORWARD_LOCATION_PREFIX)) {
                    ctx.set(FORWARD_TO_KEY,
                            StringUtils.cleanPath(location.substring(FORWARD_LOCATION_PREFIX.length()) + route.getPath()));
                    ctx.setRouteHost(null);
                    return null;
                }
                else {
              //设置服务id在RibbonReques中使用
                    // set serviceId for use in filters.route.RibbonRequest
                    ctx.set(SERVICE_ID_KEY, location);
                    ctx.setRouteHost(null);
                    ctx.addOriginResponseHeader(SERVICE_ID_HEADER, location);
                }
                if (this.properties.isAddProxyHeaders()) {
                    addProxyHeaders(ctx, route);
                    String xforwardedfor = ctx.getRequest().getHeader(X_FORWARDED_FOR_HEADER);
                    String remoteAddr = ctx.getRequest().getRemoteAddr();
                    if (xforwardedfor == null) {
                        xforwardedfor = remoteAddr;
                    }
                    else if (!xforwardedfor.contains(remoteAddr)) { // Prevent duplicates
                        xforwardedfor += ", " + remoteAddr;
                    }
                    ctx.addZuulRequestHeader(X_FORWARDED_FOR_HEADER, xforwardedfor);
                }
                if (this.properties.isAddHostHeader()) {
                    ctx.addZuulRequestHeader(HttpHeaders.HOST, toHostHeader(ctx.getRequest()));
                }

...省略...

RibbonRoutingFilter:routing过滤器,使用Ribbon和Hystrix来向服务实例发起请求 ,有服务熔断机制,执行顺序 10


/**
 * Route {@link ZuulFilter} that uses Ribbon, Hystrix and pluggable http clients to send requests.
 * ServiceIds are found in the {@link RequestContext} attribute {@link org.springframework.cloud.netflix.zuul.filters.support.FilterConstants#SERVICE_ID_KEY}.
通过  Ribbon 和  Hystrix 向http客户端发送请求
通过 RequestContext找到  ServiceIds服务id ,


 * @author Spencer Gibb
 * @author Dave Syer
 * @author Ryan Baxter
 */
public class RibbonRoutingFilter extends ZuulFilter {
...省略...

@Override
    public Object run() {
//获取请求上下文 
        RequestContext context = RequestContext.getCurrentContext();
        this.helper.addIgnoredHeaders();
        try {

//创建一个 RibbonCommandContext Ribbon命令上下文,用来发请求
            RibbonCommandContext commandContext = buildCommandContext(context);
//发送请求,获取到结果
            ClientHttpResponse response = forward(commandContext);
            setResponse(response);
            return response;
        }
        catch (ZuulException ex) {
            throw new ZuulRuntimeException(ex);
        }
        catch (Exception ex) {
            throw new ZuulRuntimeException(ex);
        }
    }

//根据RequestContext 请求上下文,获取请求服务id,url等封装成RibbonCommandContext
protected RibbonCommandContext buildCommandContext(RequestContext context) {
        HttpServletRequest request = context.getRequest();

        MultiValueMap headers = this.helper
                .buildZuulRequestHeaders(request);
        MultiValueMap params = this.helper
                .buildZuulRequestQueryParams(request);
        String verb = getVerb(request);
        InputStream requestEntity = getRequestBody(request);
        if (request.getContentLength() < 0 && !verb.equalsIgnoreCase("GET")) {
            context.setChunkedRequestBody();
        }

        String serviceId = (String) context.get(SERVICE_ID_KEY);
        Boolean retryable = (Boolean) context.get(RETRYABLE_KEY);
        Object loadBalancerKey = context.get(LOAD_BALANCER_KEY);

        String uri = this.helper.buildZuulRequestURI(request);

        // remove double slashes
        uri = uri.replace("//", "/");

        long contentLength = useServlet31 ? request.getContentLengthLong(): request.getContentLength();

        return new RibbonCommandContext(serviceId, verb, uri, retryable, headers, params,
                requestEntity, this.requestCustomizers, contentLength, loadBalancerKey);
    }

protected ClientHttpResponse forward(RibbonCommandContext context) throws Exception {
        Map info = this.helper.debug(context.getMethod(),
                context.getUri(), context.getHeaders(), context.getParams(),
                context.getRequestEntity());

        RibbonCommand command = this.ribbonCommandFactory.create(context);
        try {
//执行请求
            ClientHttpResponse response = command.execute();
            this.helper.appendDebug(info, response.getRawStatusCode(), response.getHeaders());
            return response;
        }
        catch (HystrixRuntimeException ex) {
//处理异常
            return handleException(info, ex);
        }

    }
//处理异常
protected ClientHttpResponse handleException(Map info,
            HystrixRuntimeException ex) throws ZuulException {
        int statusCode = HttpStatus.INTERNAL_SERVER_ERROR.value();
        Throwable cause = ex;
        String message = ex.getFailureType().toString();

        ClientException clientException = findClientException(ex);
        if (clientException == null) {
            clientException = findClientException(ex.getFallbackException());
        }

        if (clientException != null) {
            if (clientException
                    .getErrorType() == ClientException.ErrorType.SERVER_THROTTLED) {
                statusCode = HttpStatus.SERVICE_UNAVAILABLE.value();
            }
            cause = clientException;
            message = clientException.getErrorType().toString();
        }
        info.put("status", String.valueOf(statusCode));
        throw new ZuulException(cause, "Forwarding error", statusCode, message);
    }


SimpleHostRoutingFilter : 通过RequestContext#getRouteHost()找到调用的服务地址 ,使用http客户端实现调用 ,他和RibbonRoutingFilter的区别是没有使用Hystrix所以并没有线程隔离和断路器的保护。
执行顺序 100

/**
 * Route {@link ZuulFilter} that sends requests to predetermined URLs via apache
 * {@link HttpClient}. URLs are found in {@link RequestContext#getRouteHost()}.

通过RequestContext#getRouteHost()找到调用的服务地址 ,使用apache的http客户端实现调用
 *
 * @author Spencer Gibb
 * @author Dave Syer
 * @author Bilal Alp
 * @author Gang Li
 */
public class SimpleHostRoutingFilter extends ZuulFilter {

...省略...
@Override
    public Object run() {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        MultiValueMap headers = this.helper
                .buildZuulRequestHeaders(request);
        MultiValueMap params = this.helper
                .buildZuulRequestQueryParams(request);
        String verb = getVerb(request);
        InputStream requestEntity = getRequestBody(request);
        if (request.getContentLength() < 0) {
            context.setChunkedRequestBody();
        }

//获取请求地址
        String uri = this.helper.buildZuulRequestURI(request);
        this.helper.addIgnoredHeaders();

        try {
//发送请求
            CloseableHttpResponse response = forward(this.httpClient, verb, uri, request,
                    headers, params, requestEntity);
            setResponse(response);
        }
        catch (Exception ex) {
            throw new ZuulRuntimeException(ex);
        }
        return null;
    }
------------------------------------
//使用 httpclient 发送请求
private CloseableHttpResponse forward(CloseableHttpClient httpclient, String verb,
            String uri, HttpServletRequest request, MultiValueMap headers,
            MultiValueMap params, InputStream requestEntity)
            throws Exception {
        Map info = this.helper.debug(verb, uri, headers, params,
                requestEntity);
//请求主机
        URL host = RequestContext.getCurrentContext().getRouteHost();
        HttpHost httpHost = getHttpHost(host);
//请求地址
        uri = StringUtils.cleanPath((host.getPath() + uri).replaceAll("/{2,}", "/"));
        int contentLength = request.getContentLength();

        ContentType contentType = null;

        if (request.getContentType() != null) {
            contentType = ContentType.parse(request.getContentType());
        }

        InputStreamEntity entity = new InputStreamEntity(requestEntity, contentLength,
                contentType);

        HttpRequest httpRequest = buildHttpRequest(verb, uri, entity, headers, params,
                request);
        try {
            log.debug(httpHost.getHostName() + " " + httpHost.getPort() + " "
                    + httpHost.getSchemeName());
//发送请求
            CloseableHttpResponse zuulResponse = forwardRequest(httpclient, httpHost,
                    httpRequest);
            this.helper.appendDebug(info, zuulResponse.getStatusLine().getStatusCode(),
                    revertHeaders(zuulResponse.getAllHeaders()));
            return zuulResponse;
        }
        finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            // httpclient.getConnectionManager().shutdown();
        }
    }
------------------------------------
protected HttpRequest buildHttpRequest(String verb, String uri,
            InputStreamEntity entity, MultiValueMap headers,
            MultiValueMap params, HttpServletRequest request) {
        HttpRequest httpRequest;
        String uriWithQueryString = uri + (this.forceOriginalQueryStringEncoding
                ? getEncodedQueryString(request) : 

this.helper.getQueryString(params));
//处理各种请求方式
        switch (verb.toUpperCase()) {
        case "POST":
            HttpPost httpPost = new HttpPost(uriWithQueryString);
            httpRequest = httpPost;
            httpPost.setEntity(entity);
            break;
        case "PUT":
            HttpPut httpPut = new HttpPut(uriWithQueryString);
            httpRequest = httpPut;
            httpPut.setEntity(entity);
            break;
        case "PATCH":
            HttpPatch httpPatch = new HttpPatch(uriWithQueryString);
            httpRequest = httpPatch;
            httpPatch.setEntity(entity);
            break;
        case "DELETE":
            BasicHttpEntityEnclosingRequest entityRequest = new BasicHttpEntityEnclosingRequest(
                    verb, uriWithQueryString);
            httpRequest = entityRequest;
            entityRequest.setEntity(entity);
            break;
        default:
            httpRequest = new BasicHttpRequest(verb, uriWithQueryString);
            log.debug(uriWithQueryString);
        }

        httpRequest.setHeaders(convertHeaders(headers));
        return httpRequest;
    }
------------------------------------
//最终执行请求
private CloseableHttpResponse forwardRequest(CloseableHttpClient httpclient,
            HttpHost httpHost, HttpRequest httpRequest) throws IOException {
        return httpclient.execute(httpHost, httpRequest);
    }


到这里我们把 ZuulProxyAutoConfiguration 自动配置类中定义的比较重要的一些过滤器都介绍完了 ,zuul在执行过程中就会按照这些filter的调用顺序去执行,我们来用表格整理一下

SpringCloud-源码分析 zuul (一)_第2张图片

用表格

那这一章我们分析到这里 ,下一章我们跟踪一下zuul的执行流程,看他是如果把这些filter串联起来的 。

想获取更多技术干货,请前往叩丁狼官网:http://www.wolfcode.cn/all_article.html

你可能感兴趣的:(Spring生态)