spring 配置 zuul servlet

原创
2019/03/27 11:37
阅读数 154

zuul servlet load by spring mvc

需求:

  1. dispatcher 的请求代理至ZuulServlet, 这个设计可配置
  2. 单独/zuul的请求不经过DispatcherServlet.

我们知道zuul的整个处理逻辑在ZuulServlet中实现,但是是怎样在Spring 中和spring DispatcherServlet 一起工作的呢。

zuul config 中会加载如下的servlet:

//  "/"路径下的业务处理
@Bean
public ZuulController zuulController() {
	return new ZuulController();
}

// "/zuul" 路径的servlet处理
@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;
}
  1. ServletRegistrationBean 注册ZuulServlet的时候作为urlMapping /zuul, . 即所有来自以/zuul开头的path都会由ZuulServlet处理.

  2. ZuulController 所有进入Zuul的请求的入口都是ZuulController.

  3. ZuulHandlerMapping ZuulController的ZuulHandlerMapping默认把zuul.routes.[ITEM].path的请求交给ZuulServlet处理. 如果找不到对应的path的route, 则会走其他的DispatcherServlet

servlet context

  • Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.
  • There is one context per "web application" per Java Virtual Machine. (A "web application" is a collection of servlets and content installed under a specific subset of the server's URL namespace such as /catalog and possibly installed via a .war file.)

servlet lifecycle

spring DispatcherServlet design

关于context继承的问题,如下图所示如果应用有文件配置了/WEB-INF/golfing-servlet.xml,那么就会创建一个golfing(servlet name) WebApplicationContext,那么对应的bean会先在这个context里面找,找不到再去root中找。

其中可以自定义扩展可以让所有bean都包含在Root WebApplicationContext中,设置如下:

// This can be configured by setting an empty contextConfigLocation servlet init parameter, as shown below
<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/root-context.xml</param-value>
</context-param>

root-context 的创建时机是由ContextLoaderListener加载(servlet 容器 contextInitialized(ServletContextEvent))方法被调用。

<listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

Dispacher servlet

参考SpringMVC处理流程图

总结:

  1. spring mvc 提供了servlet的很多可扩展性设计同dispacherServlet一同工作,比如 ServletWrappingController,ServletForwardingController
  2. 我们设计一个东西的时候可以不用考虑spring 的东西,都可以很好的整合到里面,这方面的设计包括spring boot的外部化配置。

参考:

https://docs.spring.io/spring/docs/4.3.22.RELEASE/spring-framework-reference/htmlsingle/#mvc

https://github.com/Netflix/zuul/wiki/How-it-Works

https://www.cnblogs.com/zhangminghui/p/4922306.html

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部