Spring Boot启动过程(四):Spring Boot内嵌Tomcat启动

  之前在Spring Boot 启动过程(二)提到过 createEmbeddedServletContainer 创建了内嵌的 Servlet 容器,我用的是默认的 Tomcat。

    private void createEmbeddedServletContainer() {
        EmbeddedServletContainer localContainer = this.embeddedServletContainer;
        ServletContext localServletContext = getServletContext();
        if (localContainer == null && localServletContext == null) {
            EmbeddedServletContainerFactory containerFactory = getEmbeddedServletContainerFactory();
            this.embeddedServletContainer = containerFactory
                    .getEmbeddedServletContainer(getSelfInitializer());
        }
        else if (localServletContext != null) {
            try {getSelfInitializer().onStartup(localServletContext);
            }
            catch (ServletException ex) {
                throw new ApplicationContextException("Cannot initialize servlet context",
                        ex);}
        }
        initPropertySources();}

  getEmbeddedServletContainerFactory 方法中调用了 ServerProperties,从 ServerProperties 的实例方法 customize 可以看出 Springboot 支持三种内嵌容器的定制化配置:Tomcat、Jetty、Undertow。

  这里直接说 TomcatEmbeddedServletContainerFactory 的 getEmbeddedServletContainer 方法了,原因在前面那篇里说过了。不过首先是 getSelfInitializer 方法先执行的:

    private org.springframework.boot.web.servlet.ServletContextInitializer getSelfInitializer() {
        return new ServletContextInitializer() {
            @Override
            public void onStartup(ServletContext servletContext) throws ServletException {selfInitialize(servletContext);
            }
        };
    }

  将初始化的 ServletContextInitializer 传给了 getEmbeddedServletContainer 方法。进入了 getEmbeddedServletContainer 方法直接就是实例化了一个 Tomcat:

        Tomcat tomcat = new Tomcat();

   然后生成一个临时目录,并 tomcat.setBaseDir,setBaseDir 方法的注释说 Tomcat 需要一个目录用于临时文件并且它应该是第一个被调用的方法;如果方法没有被调用会使用默认的几个位置 system properties - catalina.base, catalina.home - $PWD/tomcat.$PORT,另外 /tmp 从安全角度来说不建议。

  接着:

        Connector connector = new Connector(this.protocol);

  创建 Connector 过程中,静态代码块:单独抽出来写了。RECYCLE_FACADES 属性可以通过启动参数 JAVA_OPTS 来配置: -Dorg.apache.catalina.connector.RECYCLE_FACADES=,默认是 false,配置成 true 可以提高安全性但同时性能会有些损耗,参考:http://tomcat.apache.org/tomcat-7.0-doc/config/systemprops.html 和 http://bztax.gov.cn/docs/security-howto.html。其他属性不细说了,Connector 构造的逻辑主要是在 NIO 和 APR 选择中选择一个协议,我的是 org.apache.coyote.http11.Http11NioProtocol,然后反射创建实例并强转为 ProtocolHandler。关于 apr,似乎是更 native,性能据说更好,但我没测,相关文档可参考:http://tomcat.apache.org/tomcat-8.5-doc/apr.html。这里简单提一下 coyote,它的主要作用是将 socket 接受的信息封装为 request 和 response 并提供给上 Servlet 容器,进行上下层之间的沟通,文档我没找到比较新的:http://tomcat.apache.org/tomcat-4.1-doc/config/coyote.html。STRICT_SERVLET_COMPLIANCE 也是启动参数控制,默认是 false,配置项是 org.apache.catalina.STRICT_SERVLET_COMPLIANCE,默认情况下会设置 URIEncoding = "UTF-8" 和 URIEncodingLower = URIEncoding.toLowerCase(Locale.ENGLISH),相关详细介绍可参考:http://tomcat.apache.org/tomcat-7.0-doc/config/systemprops.html。Connector 的创建过程比较关键,容我单独写一篇吧。

  Connector 实例创建好了之后 tomcat.getService().addConnector(connector),getService 的 getServer 中 new 了一个 StandardServer,StandardServer 的初始化主要是创建了 globalNamingResources(globalNamingResources 主要用于管理明明上下文和 JDNI 上下文),并根据 catalina.useNaming 判断是否注册 NamingContextListener 监听器给 lifecycleListeners。创建 Server 之后 initBaseDir,先读取 catalina.home 配置 System.getProperty(Globals.CATALINA_BASE_PROP),如果没取到则使用之前生成的临时目录,这段直接看代码吧:

    protected void initBaseDir() {
        String catalinaHome = System.getProperty(Globals.CATALINA_HOME_PROP);
        if (basedir == null) {
            basedir = System.getProperty(Globals.CATALINA_BASE_PROP);
        }
        if (basedir == null) {
            basedir = catalinaHome;
        }
        if (basedir == null) {
            // Create a temp dir.
            basedir = System.getProperty("user.dir") +
                "/tomcat." + port;
        }
    File baseFile </span>= <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> File(basedir);
    baseFile.mkdirs();
    </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)"> {
        baseFile </span>=<span style="color: rgba(0, 0, 0, 1)"> baseFile.getCanonicalFile();
    } </span><span style="color: rgba(0, 0, 255, 1)">catch</span><span style="color: rgba(0, 0, 0, 1)"> (IOException e) {
        baseFile </span>=<span style="color: rgba(0, 0, 0, 1)"> baseFile.getAbsoluteFile();
    }
    server.setCatalinaBase(baseFile);
    System.setProperty(Globals.CATALINA_BASE_PROP, baseFile.getPath());
    basedir </span>=<span style="color: rgba(0, 0, 0, 1)"> baseFile.getPath();

    </span><span style="color: rgba(0, 0, 255, 1)">if</span> (catalinaHome == <span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)">) {
        server.setCatalinaHome(baseFile);
    } </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)"> {
        File homeFile </span>= <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> File(catalinaHome);
        homeFile.mkdirs();
        </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)"> {
            homeFile </span>=<span style="color: rgba(0, 0, 0, 1)"> homeFile.getCanonicalFile();
        } </span><span style="color: rgba(0, 0, 255, 1)">catch</span><span style="color: rgba(0, 0, 0, 1)"> (IOException e) {
            homeFile </span>=<span style="color: rgba(0, 0, 0, 1)"> homeFile.getAbsoluteFile();
        }
        server.setCatalinaHome(homeFile);
    }
    System.setProperty(Globals.CATALINA_HOME_PROP,
            server.getCatalinaHome().getPath());
}</span></pre>

   然后又实例化了个 StandardService,代码并没有什么特别的:

        service = new StandardService();
        service.setName("Tomcat");
        server.addService(service)

  server.addService(service) 这里除了发布了一个 PropertyChangeEvent 事件,也没做什么特别的,最后返回这个 server。addConnector 的逻辑和上面 addService 没什么区别。然后是 customizeConnector,这里设置了 Connector 的端口、编码等信息,并将“bindOnInit”和对应值 false 写入了最开头说的静态代码块中的 replacements 集合,IntrospectionUtils.setProperty(protocolHandler, repl, value) 通过反射的方法将 protocolHandler 实现对象的 setBindOnInit 存在的情况下(拼字符串拼出来的)set 为前面的 false,这个方法里有大量的判断比如参数类型及 setter 的参数类型,比如返回值类型以及没找到还会 try a setProperty("name", "value") 等,setProperty 可以处理比如 AbstractEndpoint 中有个 HashMap<String, Object> attributes 的属性时会 attributes.put(name, value)。如果是 ssl 还会执行 customizeSsl 方法,设置一些 SSL 用的属性比如协议比如秘钥还有可以用上秘钥仓库等。如果配置了压缩,这里还会给协议的相关 setter 设置值。tomcat.setConnector(connector) 不解释。tomcat.getHost().setAutoDeploy(false),getHost 方法中创建了 StandardHost 并设置 host 名(例如 localhost),并 getEngine().addChild( host);然后设置 host 的自动部署。configureEngine(tomcat.getEngine()),getEngine 中如果 engine 为 null 就初始化标准引擎,设置名字为 Tomcat, 设置 Realm 和 service.setContainer(engine),不过这里 engine 已经在 getHost 初始化过了所以直接返回;configureEngine 方法先设置引擎的后台进程延迟,并将引擎的 Value 对象注册给引擎的 pipeline,此时尚无 value 对象实例。这里简单说明一下:value 对象在 Tomcat 的各级容器中都有标准类型,并且各级容器都有一个 pipeline,在请求处理过程中会从各级的第一个 value 对象开始依次执行一遍,value 用于加入到对应的各级容器的逻辑,默认有一个标注 value 实现,名字类似 StandardHostValue。

  prepareContext(tomcat.getHost(), initializers),initializers 这里是 AnnotationConfigEmbeddedWebApplicationContext,Context 级的根;准备 Context 的过程主要设置 Base 目录,new 一个 TomcatEmbeddedContext 并在构造中判断了下 loadOnStartup 方法是否被重写;注册一个 FixContextListener 监听,这个监听用于设置 context 的配置状态以及是否加入登录验证的逻辑;context.setParentClassLoader;设置各种语言的编码映射,我这里是 en 和 fr 设置为 UTF-8,此处可以使用配置文件 org/apache/catalina/util/CharsetMapperDefault .properties;设置是否使用相对地址重定向 useRelativeRedirects=false,此属性应该是 Tomcat 8.0.30 版本加上的;接着就是初始化 webapploader, 这里和完整版的 Tomcat 有点不一样,它用的是虚拟机的方式,会将加载类向上委托 loader.setDelegate(true),context.setLoader(loader); 之后就开始创建 Wapper 了,至此 engine,host,context 及 wrapper 四个层次的容器都创建完了:

    private void addDefaultServlet(Context context) {
        Wrapper defaultServlet = context.createWrapper();
        defaultServlet.setName("default");
        defaultServlet.setServletClass("org.apache.catalina.servlets.DefaultServlet");
        defaultServlet.addInitParameter("debug", "0");
        defaultServlet.addInitParameter("listings", "false");
        defaultServlet.setLoadOnStartup(1);
        // Otherwise the default location of a Spring DispatcherServlet cannot be set
        defaultServlet.setOverridable(true);
        context.addChild(defaultServlet);
        addServletMapping(context, "/", "default");}

   connector 从 socket 接收的数据,解析成 HttpServletRequest 后就会经过这几层容器,有容器各自的 Value 对象链依次处理。

  接着是是否注册 jspServlet,jasperInitializer 和 StoreMergedWebXmlListener 我这里是都没有的。接着的 mergeInitializers 方法:

    protected final ServletContextInitializer[] mergeInitializers(ServletContextInitializer... initializers) {
        List<ServletContextInitializer> mergedInitializers = new ArrayList<ServletContextInitializer>();
        mergedInitializers.addAll(Arrays.asList(initializers));
        mergedInitializers.addAll(this.initializers);
        return mergedInitializers
                .toArray(new ServletContextInitializer[mergedInitializers.size()]);
    }

 

  configureContext(context, initializersToUse) 对 context 做了些设置工作,包括 TomcatStarter(实例化并 set 给 context),LifecycleListener,contextValue,errorpage,Mime,session 超时持久化等以及一些自定义工作:

        TomcatStarter starter = new TomcatStarter(initializers);
        if (context instanceof TomcatEmbeddedContext) {
            // Should be true
            ((TomcatEmbeddedContext) context).setStarter(starter);
        }
        context.addServletContainerInitializer(starter, NO_CLASSES);
        for (LifecycleListener lifecycleListener : this.contextLifecycleListeners) {context.addLifecycleListener(lifecycleListener);
        }
        for (Valve valve : this.contextValves) {context.getPipeline().addValve(valve);
        }
        for (ErrorPage errorPage : getErrorPages()) {
            new TomcatErrorPage(errorPage).addToContext(context);
        }
        for (MimeMappings.Mapping mapping : getMimeMappings()) {context.addMimeMapping(mapping.getExtension(), mapping.getMimeType());}

 

  Session 如果不需要持久化会注册一个 DisablePersistSessionListener。其他定制化操作是通过 TomcatContextCustomizer 的实现类实现的:

  context 配置完了作为 child add 给 host,add 时给 context 注册了个内存泄漏跟踪的监听 MemoryLeakTrackingListener。postProcessContext(context) 方法是空的,留给子类重写用的。

   getEmbeddedServletContainer 方法的最后一行:return getTomcatEmbeddedServletContainer(tomcat)。

    protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer(Tomcat tomcat) {
        return new TomcatEmbeddedServletContainer(tomcat, getPort() >= 0);}

   TomcatEmbeddedServletContainer 的构造函数:

    public TomcatEmbeddedServletContainer(Tomcat tomcat, boolean autoStart) {
        Assert.notNull(tomcat, "Tomcat Server must not be null");
        this.tomcat = tomcat;
        this.autoStart = autoStart;
        initialize();}

  initialize 的第一个方法 addInstanceIdToEngineName 对全局原子变量 containerCounter+1,由于初始值是 -1,所以 addInstanceIdToEngineName 方法内后续的获取引擎并设置名字的逻辑没有执行:

    private void addInstanceIdToEngineName() {
        int instanceId = containerCounter.incrementAndGet();
        if (instanceId > 0) {
            Engine engine = this.tomcat.getEngine();
            engine.setName(engine.getName() + "-" + instanceId);}
    }

   initialize 的第二个方法 removeServiceConnectors,将上面 new 的 connection 以 service(这里是 StandardService[Tomcat])做 key 保存到 private final Map<Service, Connector[]> serviceConnectors 中,并将 StandardService 中的 protected Connector[] connectors 与 service 解绑 (connector.setService((Service)null);),解绑后下面利用 LifecycleBase 启动容器就不会启动到 Connector 了。

  之后是 this.tomcat.start(),这段比较复杂,我单独总结一篇吧。

  TomcatEmbeddedServletContainer 的初始化,接下来是 rethrowDeferredStartupExceptions,这个方法检查初始化过程中的异常,如果有直接在主线程抛出,检查方法是 TomcatStarter 中的 private volatile Exception startUpException,这个值是在 Context 启动过程中记录的:

    @Override
    public void onStartup(Set<Class<?>> classes, ServletContext servletContext)
            throws ServletException {
        try {
            for (ServletContextInitializer initializer : this.initializers) {initializer.onStartup(servletContext);
            }
        }
        catch (Exception ex) {
            this.startUpException = ex;
            // Prevent Tomcat from logging and re-throwing when we know we can
            // deal with it in the main thread, but log for information here.
            if (logger.isErrorEnabled()) {
                logger.error("Error starting Tomcat context. Exception:"
                        + ex.getClass().getName() + ". Message:" + ex.getMessage());}
        }
    }

  Context context = findContext():

    private Context findContext() {
        for (Container child : this.tomcat.getHost().findChildren()) {
            if (child instanceof Context) {
                return (Context) child;
            }
        }
        throw new IllegalStateException("The host does not contain a Context");}

  绑定命名的上下文和 classloader,不成功也无所谓:

                try {ContextBindings.bindClassLoader(context, getNamingToken(context),
                            getClass().getClassLoader());
                }
                catch (NamingException ex) {
                    // Naming is not enabled. Continue
                }

  startDaemonAwaitThread 方法的注释是:与 Jetty 不同,Tomcat 所有的线程都是守护线程,所以创建一个非守护线程(例:Thread[container-0,5,main])来避免服务到这就 shutdown 了:

    private void startDaemonAwaitThread() {
        Thread awaitThread = new Thread("container-" + (containerCounter.get())) {
        @Override
        </span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> run() {
            TomcatEmbeddedServletContainer.</span><span style="color: rgba(0, 0, 255, 1)">this</span><span style="color: rgba(0, 0, 0, 1)">.tomcat.getServer().await();
        }

    };
    awaitThread.setContextClassLoader(getClass().getClassLoader());
    awaitThread.setDaemon(</span><span style="color: rgba(0, 0, 255, 1)">false</span><span style="color: rgba(0, 0, 0, 1)">);
    awaitThread.start();
}</span></pre>

  这个 await 每 10 秒检查一次是否关闭了:

            try {
                awaitThread = Thread.currentThread();
                while(!stopAwait) {
                    try {
                        Thread.sleep( 10000 );} catch(InterruptedException ex) {
                        // continue and check the flag
                    }
                }
            } finally {
                awaitThread = null;
            }
            return;

  回到 EmbeddedWebApplicationContext,initPropertySources 方法,用初始化好的 servletContext 完善环境变量:

    /**
     * {@inheritDoc}
     * <p>Replace {@code Servlet}-related property sources.
     */
    @Override
    protected void initPropertySources() {
        ConfigurableEnvironment env = getEnvironment();
        if (env instanceof ConfigurableWebEnvironment) {((ConfigurableWebEnvironment) env).initPropertySources(this.servletContext, null);}
    }

  createEmbeddedServletContainer 就结束了,内嵌容器的启动过程至此结束。

==========================================================

咱最近用的 github:https://github.com/saaavsaaa

微信公众号: