- 資訊首頁(yè) > 開(kāi)發(fā)技術(shù) > 編程語(yǔ)言 >
- SpringBoot內置tomcat啟動(dòng)原理詳解
不得不說(shuō)SpringBoot的開(kāi)發(fā)者是在為大眾程序猿謀福利,把大家都慣成了懶漢,xml不配置了,連tomcat也懶的配置了,典型的一鍵啟動(dòng)系統,那么tomcat在springboot是怎么啟動(dòng)的呢?
開(kāi)發(fā)階段對我們來(lái)說(shuō)使用內置的tomcat是非常夠用了,當然也可以使用jetty。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.1.6.RELEASE</version> </dependency>
@SpringBootApplication public class MySpringbootTomcatStarter{ public static void main(String[] args) { Long time=System.currentTimeMillis(); SpringApplication.run(MySpringbootTomcatStarter.class); System.out.println("===應用啟動(dòng)耗時(shí):"+(System.currentTimeMillis()-time)+"==="); } }
這里是main函數入口,兩句代碼最耀眼,分別是SpringBootApplication注解和SpringApplication.run()方法。
發(fā)布的時(shí)候,目前大多數的做法還是排除內置的tomcat,打瓦包(war)然后部署在生產(chǎn)的tomcat中,好吧,那打包的時(shí)候應該怎么處理?
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <!-- 移除嵌入式tomcat插件 --> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency> <!--添加servlet-api依賴(lài)---> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency>
更新main函數,主要是繼承SpringBootServletInitializer,并重寫(xiě)configure()方法。
@SpringBootApplication public class MySpringbootTomcatStarter extends SpringBootServletInitializer { public static void main(String[] args) { Long time=System.currentTimeMillis(); SpringApplication.run(MySpringbootTomcatStarter.class); System.out.println("===應用啟動(dòng)耗時(shí):"+(System.currentTimeMillis()-time)+"==="); } @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { return builder.sources(this.getClass()); } }
public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) { return run(new Class[]{primarySource}, args); }
--這里run方法返回的是ConfigurableApplicationContext
public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) { return (new SpringApplication(primarySources)).run(args); }
public ConfigurableApplicationContext run(String... args) { ConfigurableApplicationContext context = null; Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList(); this.configureHeadlessProperty(); SpringApplicationRunListeners listeners = this.getRunListeners(args); listeners.starting(); Collection exceptionReporters; try { ApplicationArguments applicationArguments = new DefaultApplicationArguments(args); ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments); this.configureIgnoreBeanInfo(environment); //打印banner,這里你可以自己涂鴉一下,換成自己項目的logo Banner printedBanner = this.printBanner(environment); //創(chuàng )建應用上下文 context = this.createApplicationContext(); exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context); //預處理上下文 this.prepareContext(context, environment, listeners, applicationArguments, printedBanner); //刷新上下文 this.refreshContext(context); //再刷新上下文 this.afterRefresh(context, applicationArguments); listeners.started(context); this.callRunners(context, applicationArguments); } catch (Throwable var10) { } try { listeners.running(context); return context; } catch (Throwable var9) { } }
既然我們想知道tomcat在SpringBoot中是怎么啟動(dòng)的,那么run方法中,重點(diǎn)關(guān)注創(chuàng )建應用上下文(createApplicationContext)和刷新上下文(refreshContext)。
//創(chuàng )建上下文 protected ConfigurableApplicationContext createApplicationContext() { Class<?> contextClass = this.applicationContextClass; if (contextClass == null) { try { switch(this.webApplicationType) { case SERVLET: //創(chuàng )建AnnotationConfigServletWebServerApplicationContext contextClass = Class.forName("org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext"); break; case REACTIVE: contextClass = Class.forName("org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext"); break; default: contextClass = Class.forName("org.springframework.context.annotation.AnnotationConfigApplicationContext"); } } catch (ClassNotFoundException var3) { throw new IllegalStateException("Unable create a default ApplicationContext, please specify an ApplicationContextClass", var3); } } return (ConfigurableApplicationContext)BeanUtils.instantiateClass(contextClass); }
這里會(huì )創(chuàng )建AnnotationConfigServletWebServerApplicationContext類(lèi)。
而AnnotationConfigServletWebServerApplicationContext類(lèi)繼承了ServletWebServerApplicationContext,而這個(gè)類(lèi)是最終集成了AbstractApplicationContext。
//SpringApplication.java //刷新上下文 private void refreshContext(ConfigurableApplicationContext context) { this.refresh(context); if (this.registerShutdownHook) { try { context.registerShutdownHook(); } catch (AccessControlException var3) { } } }
//這里直接調用最終父類(lèi)AbstractApplicationContext.refresh()方法 protected void refresh(ApplicationContext applicationContext) { ((AbstractApplicationContext)applicationContext).refresh(); } //AbstractApplicationContext.java public void refresh() throws BeansException, IllegalStateException { synchronized(this.startupShutdownMonitor) { this.prepareRefresh(); ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory(); this.prepareBeanFactory(beanFactory); try { this.postProcessBeanFactory(beanFactory); this.invokeBeanFactoryPostProcessors(beanFactory); this.registerBeanPostProcessors(beanFactory); this.initMessageSource(); this.initApplicationEventMulticaster(); //調用各個(gè)子類(lèi)的onRefresh()方法,也就說(shuō)這里要回到子類(lèi):ServletWebServerApplicationContext,調用該類(lèi)的onRefresh()方法 this.onRefresh(); this.registerListeners(); this.finishBeanFactoryInitialization(beanFactory); this.finishRefresh(); } catch (BeansException var9) { this.destroyBeans(); this.cancelRefresh(var9); throw var9; } finally { this.resetCommonCaches(); } } }
//ServletWebServerApplicationContext.java //在這個(gè)方法里看到了熟悉的面孔,this.createWebServer,神秘的面紗就要揭開(kāi)了。 protected void onRefresh() { super.onRefresh(); try { this.createWebServer(); } catch (Throwable var2) { } } //ServletWebServerApplicationContext.java //這里是創(chuàng )建webServer,但是還沒(méi)有啟動(dòng)tomcat,這里是通過(guò)ServletWebServerFactory創(chuàng )建,那么接著(zhù)看下ServletWebServerFactory private void createWebServer() { WebServer webServer = this.webServer; ServletContext servletContext = this.getServletContext(); if (webServer == null && servletContext == null) { ServletWebServerFactory factory = this.getWebServerFactory(); this.webServer = factory.getWebServer(new ServletContextInitializer[]{this.getSelfInitializer()}); } else if (servletContext != null) { try { this.getSelfInitializer().onStartup(servletContext); } catch (ServletException var4) { } } this.initPropertySources(); } //接口 public interface ServletWebServerFactory { WebServer getWebServer(ServletContextInitializer... initializers); } //實(shí)現 AbstractServletWebServerFactory JettyServletWebServerFactory TomcatServletWebServerFactory UndertowServletWebServerFactory
這里ServletWebServerFactory接口有4個(gè)實(shí)現類(lèi)
而其中我們常用的有兩個(gè):TomcatServletWebServerFactory和JettyServletWebServerFactory。
//TomcatServletWebServerFactory.java //這里我們使用的tomcat,所以我們查看TomcatServletWebServerFactory。到這里總算是看到了tomcat的蹤跡。 @Override public WebServer getWebServer(ServletContextInitializer... initializers) { Tomcat tomcat = new Tomcat(); File baseDir = (this.baseDirectory != null) ? this.baseDirectory : createTempDir("tomcat"); tomcat.setBaseDir(baseDir.getAbsolutePath()); //創(chuàng )建Connector對象 Connector connector = new Connector(this.protocol); tomcat.getService().addConnector(connector); customizeConnector(connector); tomcat.setConnector(connector); tomcat.getHost().setAutoDeploy(false); configureEngine(tomcat.getEngine()); for (Connector additionalConnector : this.additionalTomcatConnectors) { tomcat.getService().addConnector(additionalConnector); } prepareContext(tomcat.getHost(), initializers); return getTomcatWebServer(tomcat); } protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) { return new TomcatWebServer(tomcat, getPort() >= 0); } //Tomcat.java //返回Engine容器,看到這里,如果熟悉tomcat源碼的話(huà),對engine不會(huì )感到陌生。 public Engine getEngine() { Service service = getServer().findServices()[0]; if (service.getContainer() != null) { return service.getContainer(); } Engine engine = new StandardEngine(); engine.setName( "Tomcat" ); engine.setDefaultHost(hostname); engine.setRealm(createDefaultRealm()); service.setContainer(engine); return engine; } //Engine是最高級別容器,Host是Engine的子容器,Context是Host的子容器,Wrapper是Context的子容器
getWebServer這個(gè)方法創(chuàng )建了Tomcat對象,并且做了兩件重要的事情:把Connector對象添加到tomcat中,configureEngine(tomcat.getEngine());
getWebServer方法返回的是TomcatWebServer。
//TomcatWebServer.java //這里調用構造函數實(shí)例化TomcatWebServer public TomcatWebServer(Tomcat tomcat, boolean autoStart) { Assert.notNull(tomcat, "Tomcat Server must not be null"); this.tomcat = tomcat; this.autoStart = autoStart; initialize(); } private void initialize() throws WebServerException { //在控制臺會(huì )看到這句日志 logger.info("Tomcat initialized with port(s): " + getPortsDescription(false)); synchronized (this.monitor) { try { addInstanceIdToEngineName(); Context context = findContext(); context.addLifecycleListener((event) -> { if (context.equals(event.getSource()) && Lifecycle.START_EVENT.equals(event.getType())) { removeServiceConnectors(); } }); //===啟動(dòng)tomcat服務(wù)=== this.tomcat.start(); rethrowDeferredStartupExceptions(); try { ContextBindings.bindClassLoader(context, context.getNamingToken(), getClass().getClassLoader()); } catch (NamingException ex) { } //開(kāi)啟阻塞非守護進(jìn)程 startDaemonAwaitThread(); } catch (Exception ex) { stopSilently(); destroySilently(); throw new WebServerException("Unable to start embedded Tomcat", ex); } } } //Tomcat.java public void start() throws LifecycleException { getServer(); server.start(); } //這里server.start又會(huì )回到TomcatWebServer的 public void stop() throws LifecycleException { getServer(); server.stop(); }
//TomcatWebServer.java //啟動(dòng)tomcat服務(wù) @Override public void start() throws WebServerException { synchronized (this.monitor) { if (this.started) { return; } try { addPreviouslyRemovedConnectors(); Connector connector = this.tomcat.getConnector(); if (connector != null && this.autoStart) { performDeferredLoadOnStartup(); } checkThatConnectorsHaveStarted(); this.started = true; //在控制臺打印這句日志,如果在yml設置了上下文,這里會(huì )打印 logger.info("Tomcat started on port(s): " + getPortsDescription(true) + " with context path '" + getContextPath() + "'"); } catch (ConnectorStartFailedException ex) { stopSilently(); throw ex; } catch (Exception ex) { throw new WebServerException("Unable to start embedded Tomcat server", ex); } finally { Context context = findContext(); ContextBindings.unbindClassLoader(context, context.getNamingToken(), getClass().getClassLoader()); } } } //關(guān)閉tomcat服務(wù) @Override public void stop() throws WebServerException { synchronized (this.monitor) { boolean wasStarted = this.started; try { this.started = false; try { stopTomcat(); this.tomcat.destroy(); } catch (LifecycleException ex) { } } catch (Exception ex) { throw new WebServerException("Unable to stop embedded Tomcat", ex); } finally { if (wasStarted) { containerCounter.decrementAndGet(); } } } }
附:tomcat頂層結構圖
tomcat最頂層容器是Server,代表著(zhù)整個(gè)服務(wù)器,一個(gè)Server包含多個(gè)Service。從上圖可以看除Service主要包括多個(gè)Connector和一個(gè)Container。Connector用來(lái)處理連接相關(guān)的事情,并提供Socket到Request和Response相關(guān)轉化。Container用于封裝和管理Servlet,以及處理具體的Request請求。那么上文提到的Engine>Host>Context>Wrapper容器又是怎么回事呢? 我們來(lái)看下圖:
綜上所述,一個(gè)tomcat只包含一個(gè)Server,一個(gè)Server可以包含多個(gè)Service,一個(gè)Service只有一個(gè)Container,但有多個(gè)Connector,這樣一個(gè)服務(wù)可以處理多個(gè)連接。
多個(gè)Connector和一個(gè)Container就形成了一個(gè)Service,有了Service就可以對外提供服務(wù)了,但是Service要提供服務(wù)又必須提供一個(gè)宿主環(huán)境,那就非Server莫屬了,所以整個(gè)tomcat的聲明周期都由Server控制。
SpringBoot的啟動(dòng)主要是通過(guò)實(shí)例化SpringApplication來(lái)啟動(dòng)的,啟動(dòng)過(guò)程主要做了以下幾件事情:配置屬性、獲取監聽(tīng)器,發(fā)布應用開(kāi)始啟動(dòng)事件初、始化輸入參數、配置環(huán)境,輸出banner、創(chuàng )建上下文、預處理上下文、刷新上下文、再刷新上下文、發(fā)布應用已經(jīng)啟動(dòng)事件、發(fā)布應用啟動(dòng)完成事件。在SpringBoot中啟動(dòng)tomcat的工作在刷新上下這一步。而tomcat的啟動(dòng)主要是實(shí)例化兩個(gè)組件:Connector、Container,一個(gè)tomcat實(shí)例就是一個(gè)Server,一個(gè)Server包含多個(gè)Service,也就是多個(gè)應用程序,每個(gè)Service包含多個(gè)Connector和一個(gè)Container,而一個(gè)Container下又包含多個(gè)子容器。
到此這篇關(guān)于SpringBoot內置tomcat啟動(dòng)原理詳解的文章就介紹到這了,更多相關(guān)SpringBoot內置tomcat啟動(dòng)內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自本網(wǎng)站內容采集于網(wǎng)絡(luò )互聯(lián)網(wǎng)轉載等其它媒體和分享為主,內容觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如侵犯了原作者的版權,請告知一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容,聯(lián)系我們QQ:712375056,同時(shí)歡迎投稿傳遞力量。
Copyright ? 2009-2022 56dr.com. All Rights Reserved. 特網(wǎng)科技 特網(wǎng)云 版權所有 特網(wǎng)科技 粵ICP備16109289號
域名注冊服務(wù)機構:阿里云計算有限公司(萬(wàn)網(wǎng)) 域名服務(wù)機構:煙臺帝思普網(wǎng)絡(luò )科技有限公司(DNSPod) CDN服務(wù):阿里云計算有限公司 百度云 中國互聯(lián)網(wǎng)舉報中心 增值電信業(yè)務(wù)經(jīng)營(yíng)許可證B2
建議您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流瀏覽器瀏覽本網(wǎng)站