Spring Cloud Netflix 之 Zuul网关;过滤器filter
Zuul网关
Zuul 包含了对请求的路由和过滤两个最主要的功能,外加代理功能:
1、路由功能负责将外部请求转发到具体的微服务实例上,是实现外部访问统一入口的基础。
2、过滤器功能则负责对请求的处理过程进行干预,是实现请求校验,服务聚合等功能的基础
2、过滤器
过滤器 (filter) 是zuul的核心组件,主要作用:限流、权限验证、记录日志。
zuul中定义了4种标准过滤器类型,这些过滤器类型对应于请求的典型生命周期。
**PRE:**这种过滤器在请求被路由之前调用。可利用这种过滤器实现身份验证、在 集群中选择请求的微服务、记录调试信息等。
**ROUTING:**这种过滤器将请求路由到微服务。这种过滤器用于构建发送给微服 务的请求,并使用 Apache HttpClient或 Netfilx Ribbon请求微服务
**POST:**这种过滤器在路由到微服务以后执行。这种过滤器可用来为响应添加标准 的 HTTP Header、收集统计信息和指标、将响应从微服务发送给客户端等。 ERROR:在其他阶段发生错误时执行该过滤器。
ERROR:在其他阶段发生错误时执行该过滤器。

1、Zuul 过滤器使用
编写一个过滤器,则需继承ZuulFilter类实现其中的方法
public class LogFilter extends ZuulFilter {
/**
* filterType: 返回过滤器的类型。有 pre、 route、 post、 error等几种取值,分别对应上文的几种过滤器。
* 在路由的时候执行
* 详细可以参考 com.netflix.zuul.ZuulFilter.filterType()中的注释
*/
@Override
public String filterType() {
return FilterConstants.ROUTE_TYPE;
}
/**
* filter0rder: 返回一个 int值来指定过滤器的执行顺序,不同的过滤器允许返回相同的数字
*/
@Override
public int filterOrder() {
return FilterConstants.PRE_DECORATION_FILTER_ORDER;
}
/**
* shouldFilter:是否要使用过滤器
* 返回一个 boolean值来判断该过滤器是否要执行, true表示执行, false表示不执行
*/
@Override
public boolean shouldFilter() {
//true表示要使用该过滤,false表示不使用该过滤器(默认false)
return true;
}
/**
* run:过滤器的具体逻辑
* 在路由的时候执行run方法
*/
@Override
public Object run() throws ZuulException {
RequestContext context = RequestContext.getCurrentContext();
HttpServletRequest request = context.getRequest();
String remoteAddress = request.getServerName();
System.out.println("访问地址:" + remoteAddress + request.getRequestURI());
//接收到参数
/*request.getParameter("username");
HttpServletResponse response = currentContext.getResponse();
try {
//重定向
response.sendRedirect("");
//forward跳转
RequestDispatcher dispatcher = request.getRequestDispatcher("/path");
dispatcher.forward(request, response);
} catch (IOException e) {
e.printStackTrace();
} catch (ServletException e) {
e.printStackTrace();
}*/
//异常处理使用
int a = 10 / 0;
//返回值目前是没有什么意义的,返回null即可
return null;
}
}