Spring Cloud Netflix Zuul

1. FilterConstants

org.springframework.cloud.netflix.zuul.filters.support.FilterConstants中,可以看到Zuul定义了Filter的类型(Type)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public final class FilterConstants {

//省略...

// Zuul Filter TYPE constants -----------------------------------

/**
* {@link ZuulFilter#filterType()} error type.
*/
public static final String ERROR_TYPE = "error";

/**
* {@link ZuulFilter#filterType()} post type.
*/
public static final String POST_TYPE = "post";

/**
* {@link ZuulFilter#filterType()} pre type.
*/
public static final String PRE_TYPE = "pre";

/**
* {@link ZuulFilter#filterType()} route type.
*/
public static final String ROUTE_TYPE = "route";

//省略...

}

2. ZuulServlet

com.netflix.zuul.http.ZuulServlet中,可以看到不同类型的Filter的执行顺序。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public class ZuulServlet extends HttpServlet {

//省略...

@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();
}
}

//省略...

}