1.zuul 1.x的架构如下所示:

线程模型:

其web应用的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5"> <listener>
<listener-class>com.netflix.zuul.StartServer</listener-class>
</listener> <servlet>
<servlet-name>ZuulServlet</servlet-name>
<servlet-class>com.netflix.zuul.http.ZuulServlet</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>ZuulServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping> <filter>
<filter-name>ContextLifecycleFilter</filter-name>
<filter-class>com.netflix.zuul.context.ContextLifecycleFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ContextLifecycleFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> </web-app>

从上面可以看出,启动时有三个主类:

1.1. StartServer

    @Override
public void contextInitialized(ServletContextEvent sce) {
logger.info("starting server"); // mocks monitoring infrastructure as we don't need it for this simple app
MonitoringHelper.initMocks(); // initializes groovy filesystem poller
initGroovyFilterManager(); // initializes a few java filter examples
initJavaFilters();
}

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

1.3. ContextLifecycleFilter

public class ContextLifecycleFilter implements Filter {

    public void destroy() {}

    public void init(FilterConfig filterConfig) throws ServletException {}

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
try {
chain.doFilter(req, res);
} finally {
RequestContext.getCurrentContext().unset();
}
} }

2. zuul2的线程模型

其应用的web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5"> <filter>
<filter-name>guiceFilter</filter-name>
<filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
</filter> <filter-mapping>
<filter-name>guiceFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <listener>
<listener-class>com.netflix.zuul.StartServer</listener-class>
</listener> </web-app>

2.1. StartServer

 /**
* Overridden solely so we can tell how much time is being spent in overall initialization. Without
* overriding we can't tell how much time was spent in BaseServer doing its own initialization.
*
* @param sce
*/
@Override
public void contextInitialized(ServletContextEvent sce) {
try {
server.start();
} catch (Exception e) {
LOG.error("Error while starting karyon.", e);
throw Throwables.propagate(e);
}
try {
initialize();
} catch (Exception e) {
e.printStackTrace();
}
super.contextInitialized(sce);
}

2.2. ZuulServlet

   @Override
public void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException
{
try {
zuulProcessor
.process(servletRequest, servletResponse)
.doOnNext(msg -> {
// Store this response as an attribute for any later ServletFilters that may want access to info in it.
servletRequest.setAttribute("_zuul_response", msg);
})
.subscribe();
}
catch (Throwable e) {
LOG.error("Unexpected error running ZuulHttpProcessor for this request.", e);
throw new ServletException("Unexpected error running ZuulHttpProcessor for this request.");
}
}

2.3 ZuulHttpProcessor

/**
* The main processing class for Zuul.
*
* 1. Translates the inbound native request (ie. HttpServletRequest, or rxnetty HttpServerRequest) into a zuul HttpRequestMessage.
* 2. Builds the filter chain and passes the request through it.
* 3. Writes out the HttpResponseMessage to the native response object.
*/

处理过程:

  public Observable<ZuulMessage> process(final I nativeRequest, final O nativeResponse)
{
// Setup the context for this request.
final SessionContext context; // Optionally decorate the context.
if (decorator == null) {
context = new SessionContext();
} else {
context = decorator.decorate(new SessionContext());
} return Observable.defer((Func0<Observable<ZuulMessage>>) () -> { // Build a ZuulMessage from the netty request.
final ZuulMessage request = contextFactory.create(context, nativeRequest, nativeResponse); // Start timing the request.
request.getContext().getTimings().getRequest().start(); /*
* Delegate all of the filter application logic to {@link FilterProcessor}.
* This work is some combination of synchronous and asynchronous.
*/
Observable<ZuulMessage> chain = filterProcessor.applyFilterChain(request); return chain
.flatMap(msg -> {
// Wrap this in a try/catch because we need to ensure no exception stops the observable, as
// we need the following doOnNext to always run - as it records metrics.
try {
// Write out the response.
return contextFactory.write(msg, nativeResponse);
}
catch (Exception e) {
LOG.error("Error in writing response! request=" + request.getInfoForLogging(), e); // Generate a default error response to be sent to client.
return Observable.just(new HttpResponseMessageImpl(context, ((HttpResponseMessage) msg).getOutboundRequest(), 500));
}
finally {
// End the timing.
msg.getContext().getTimings().getRequest().end();
}
})
.doOnError(e -> {
LOG.error("Unexpected error in filter chain! request=" + request.getInfoForLogging(), e);
})
.doOnNext(msg -> {
// Notify requestComplete listener if configured.
try {
if (requestCompleteHandler != null)
requestCompleteHandler.handle(((HttpRequestMessage) request).getInboundRequest(), (HttpResponseMessage) msg);
}
catch (Exception e) {
LOG.error("Error in RequestCompleteHandler.", e);
}
})
;
}).finallyDo(() -> {
// Cleanup any resources related to this request/response.
sessionCleaner.cleanup(context);
});
}
}

参考文献:

【1】http://techblog.netflix.com/2013/06/announcing-zuul-edge-service-in-cloud.html

【2】http://techblog.netflix.com/2016/09/zuul-2-netflix-journey-to-asynchronous.html?utm_source=tuicool&utm_medium=referral

netflix zuul 1.x与zuul2.x之比较的更多相关文章

  1. Netflix Zuul 了解

    Zuul 是提供动态路由,监控,弹性,安全等的边缘服务.Zuul 相当于是设备和 Netflix 流应用的 Web 网站后端所有请求的前门.Zuul 可以适当的对多个 Amazon Auto Scal ...

  2. netflix zuul 学习

    netflix zuul 是netflix开发的一个EDGE SERVICE. 主要是作为一个API Gateway 服务器,可以实现安全,流量控制等功能. 我看的是1.x的版本,Zuul1.x的实现 ...

  3. com.netflix.zuul.exception.ZuulException: Hystrix Readed time out

    通过API网关路由来访问用户服务,zuul默认路由规则 :http://zuul的Host地址:zuul端口/要调用的服务名/服务方法地址 浏览器中打开http://127.0.0.1:8000/wa ...

  4. 聊聊 API Gateway 和 Netflix Zuul

    最近参与了公司 API Gateway 的搭建工作,技术选型是 Netflix Zuul,主要聊一聊其中的一些心得和体会. 本文主要是介绍使用 Zuul 且在不强制使用其他 Neflix OSS 组件 ...

  5. 关于SpringCloud配置网关转发时出现一下啊错误:“com.netflix.zuul.exception.ZuulException: Forwarding error at org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter.handleException”

    com.netflix.zuul.exception.ZuulException: Forwarding error at org.springframework.cloud.netflix.zuul ...

  6. Spring Cloud Netflix Zuul 重试会自动跳过经常超时的服务实例的简单说明和分析

    在使用E版本的Spring Cloud Netflix Zuul内置的Ribbon重试功能时,发现Ribbon有一个非常有用的特性: 如果某个服务的某个实例经常需要重试,Ribbon则会在自己维护的一 ...

  7. com.netflix.zuul.exception.ZuulException: Forwarding error

    一.问题描述 在使用Spring Cloud的zuul组件,做路由转发时,每次重新启动后端服务,头几次调用都会出现com.netflix.zuul.exception.ZuulException: F ...

  8. 启动zuul时候报错:The bean 'proxyRequestHelper', defined in class path resource [org/springframework/cloud/netflix/zuul

    启动zuul时候报错:The bean 'proxyRequestHelper', defined in class path resource [org/springframework/cloud/ ...

  9. springcloud初次zuul超时报错com.netflix.zuul.exception.ZuulException:Forwarding error

    报错如下 com.netflix.zuul.exception.ZuulException:Forwarding error Caused by: com.netflix.hystrix.except ...

随机推荐

  1. linux 下的小知识

    Linux中有7种启动级别 运行级别0:系统停机状态,系统默认运行级别不能设为0,否则不能正常启动运行级别1:单用户工作状态,root权限,用于系统维护,禁止远程登陆运行级别2:多用户状态(没有NFS ...

  2. 特斯拉正加快部署第三代Autopilot自动驾驶计算机

    新浪科技讯,北京时间 4 月 10 日下午消息,据电动汽车新闻网站 Electrek 报道,特斯拉正在加快部署第三代 Autopilot 自动驾驶计算机,因为当前一代产品的计算能力即将被耗尽. 201 ...

  3. Zookeeper入门-Linux环境下异常ConnectionLossException解决

    实际项目开发中,用的是Linux环境.  中午突然断电,死活连不上Zookeeper,最终发现是需要关闭防火墙.    看日志,报错如下:  Exception in thread "mai ...

  4. 安装spark问题汇总

    使用的版本是 spark-1.6.3-bin-without-hadoop 运行spark-shell报错 运行spark-sql报错找不到org.datanucleus.api.jdo.JDOPer ...

  5. spark一些入门资料

    spark一些入门资料 A Scala Tutorial for Java Programmers http://docs.scala-lang.org/tutorials/scala-for-jav ...

  6. bzoj1430: 小猴打架(prufer序列)

    1430: 小猴打架 题目:传送门 简要题意: n只互不相识的猴子打架,打架之后就两两之间连边(表示已经相互认识),只有不认识(朋友的朋友都是朋友)的两只猴子才会打架.最后所有的猴子都会连成一棵树,也 ...

  7. hdoj--5562--Clarke and food(模拟)

    Clarke and food Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others) ...

  8. TortoiseGit配合msysGit在Git@OSC代码托管的傻瓜教程

    命令行太麻烦,肿么破?便便利用睡觉的时间解决了一点效率问题,tortoiseGit处理GitHub,一样可以处理 Git @osc ,虽然说可以用gitk来调出图形界面,but,我就是不想看见黑黑的命 ...

  9. 14.hash_set(已过时,被unorded_set替代)

    #define _SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS #include <iostream> #include <hash_set> ...

  10. java9新特性-17-智能Java编译工具

    1.官方Feature 139: Enhance javac to Improve Build Speed. 199: Smart Java Compilation, Phase Two 2.使用说明 ...