0%

zuul过滤器

zuul过滤器

zuul有四种类型的过滤器

  • pre 请求被路由之前调用
  • route 路由请求时调用,用来发送请求给其他服务,大部分工作为转换请求和响应数据
  • post 在route和error之后调用
  • error 处理发生错误时调用
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
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
try {
init((HttpServletRequest) servletRequest, (HttpServletResponse) servletResponse);
try {
preRouting();
} catch (ZuulException e) {
error(e);
postRouting();
return;
}

// Only forward onto to the chain if a zuul response is not being sent
if (!RequestContext.getCurrentContext().sendZuulResponse()) {
filterChain.doFilter(servletRequest, servletResponse);
return;
}

try {
routing();
} catch (ZuulException e) {
error(e);
postRouting();
return;
}
try {
postRouting();
} catch (ZuulException e) {
error(e);
return;
}
} catch (Throwable e) {
error(new ZuulException(e, 500, "UNCAUGHT_EXCEPTION_FROM_FILTER_" + e.getClass().getName()));
} finally {
RequestContext.getCurrentContext().unset();
}
}

自定义过滤器

继承ZuulFilter抽象类

1
2
3
4
5
6
7
8
9
10
11
// 过滤器类型,pre、route、post、error
abstract public String filterType();

// 过滤器的执行顺序
abstract public int filterOrder();

// 是否需要执行
boolean shouldFilter();

// 执行逻辑
Object run();