偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

總在說(shuō)SpringBoot內(nèi)置了tomcat啟動(dòng),那它的原理你說(shuō)的清楚嗎?

開(kāi)發(fā) 后端
不得不說(shuō)SpringBoot的開(kāi)發(fā)者是在為大眾程序猿謀福利,把大家都慣成了懶漢,xml不配置了,連tomcat也懶的配置了,典型的一鍵啟動(dòng)系統(tǒng),那么tomcat在springboot是怎么啟動(dòng)的呢?來(lái)看看吧。

前言

不得不說(shuō)SpringBoot的開(kāi)發(fā)者是在為大眾程序猿謀福利,把大家都慣成了懶漢,xml不配置了,連tomcat也懶的配置了,典型的一鍵啟動(dòng)系統(tǒng),那么tomcat在springboot是怎么啟動(dòng)的呢?

內(nèi)置tomcat

開(kāi)發(fā)階段對(duì)我們來(lái)說(shuō)使用內(nèi)置的tomcat是非常夠用了,當(dāng)然也可以使用jetty。 

  1. <dependency>  
  2.    <groupId>org.springframework.boot</groupId>  
  3.    <artifactId>spring-boot-starter-web</artifactId>  
  4.    <version>2.1.6.RELEASE</version>  
  5. </dependency>  
  1. @SpringBootApplication  
  2. public class MySpringbootTomcatStarter{  
  3.     public static void main(String[] args) {  
  4.         Long time=System.currentTimeMillis();  
  5.         SpringApplication.run(MySpringbootTomcatStarter.class);  
  6.         System.out.println("===應(yīng)用啟動(dòng)耗時(shí):"+(System.currentTimeMillis()-time)+"===");  
  7.     }  

這里是main函數(shù)入口,兩句代碼最耀眼,分別是SpringBootApplication注解和SpringApplication.run()方法。

發(fā)布生產(chǎn)

發(fā)布的時(shí)候,目前大多數(shù)的做法還是排除內(nèi)置的tomcat,打瓦包(war)然后部署在生產(chǎn)的tomcat中,好吧,那打包的時(shí)候應(yīng)該怎么處理? 

  1. <dependency>  
  2.     <groupId>org.springframework.boot</groupId>  
  3.     <artifactId>spring-boot-starter-web</artifactId>  
  4.     <!-- 移除嵌入式tomcat插件 -->  
  5.     <exclusions>  
  6.         <exclusion>  
  7.             <groupId>org.springframework.boot</groupId>  
  8.             <artifactId>spring-boot-starter-tomcat</artifactId>  
  9.         </exclusion>  
  10.     </exclusions>  
  11. </dependency>  
  12. <!--添加servlet-api依賴(lài)--->  
  13. <dependency>  
  14.     <groupId>javax.servlet</groupId>  
  15.     <artifactId>javax.servlet-api</artifactId>  
  16.     <version>3.1.0</version>  
  17.     <scope>provided</scope>  
  18. </dependency> 

更新main函數(shù),主要是繼承SpringBootServletInitializer,并重寫(xiě)configure()方法。 

  1. @SpringBootApplication  
  2. public class MySpringbootTomcatStarter extends SpringBootServletInitializer {  
  3.     public static void main(String[] args) {  
  4.         Long time=System.currentTimeMillis();  
  5.         SpringApplication.run(MySpringbootTomcatStarter.class);  
  6.         System.out.println("===應(yīng)用啟動(dòng)耗時(shí):"+(System.currentTimeMillis()-time)+"===");  
  7.     } 
  8.     @Override  
  9.     protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {  
  10.         return builder.sources(this.getClass());  
  11.     }  

從main函數(shù)說(shuō)起 

  1. public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {  
  2.     return run(new Class[]{primarySource}, args);  
  3.  
  4. --這里run方法返回的是ConfigurableApplicationContext  
  5. public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {  
  6.  return (new SpringApplication(primarySources)).run(args);  
  7.  
  1. public ConfigurableApplicationContext run(String... args) {  
  2.  ConfigurableApplicationContext context = null 
  3.  Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList();  
  4.  this.configureHeadlessProperty();  
  5.  SpringApplicationRunListeners listeners = this.getRunListeners(args);  
  6.  listeners.starting();  
  7.  Collection exceptionReporters;  
  8.  try {  
  9.   ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);  
  10.   ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);  
  11.   this.configureIgnoreBeanInfo(environment);  
  12.   //打印banner,這里你可以自己涂鴉一下,換成自己項(xiàng)目的logo  
  13.   Banner printedBanner = this.printBanner(environment);   
  14.   //創(chuàng)建應(yīng)用上下文  
  15.   context = this.createApplicationContext();  
  16.   exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);  
  17.   //預(yù)處理上下文  
  18.   this.prepareContext(context, environment, listeners, applicationArguments, printedBanner); 
  19.    //刷新上下文 
  20.    this.refreshContext(context); 
  21.    //再刷新上下文  
  22.   this.afterRefresh(context, applicationArguments);  
  23.    listeners.started(context);  
  24.   this.callRunners(context, applicationArguments);  
  25.  } catch (Throwable var10) {      
  26.  }  
  27.  try {  
  28.   listeners.running(context);  
  29.   return context;  
  30.  } catch (Throwable var9) {      
  31.  }  

既然我們想知道tomcat在SpringBoot中是怎么啟動(dòng)的,那么run方法中,重點(diǎn)關(guān)注創(chuàng)建應(yīng)用上下文(createApplicationContext)和刷新上下文(refreshContext)。

創(chuàng)建上下文 

  1. //創(chuàng)建上下文  
  2. protected ConfigurableApplicationContext createApplicationContext() {  
  3.  Class<?> contextClass = this.applicationContextClass;  
  4.  if (contextClass == null) {  
  5.   try {  
  6.    switch(this.webApplicationType) {  
  7.     case SERVLET:  
  8.                     //創(chuàng)建AnnotationConfigServletWebServerApplicationContext  
  9.         contextClass = Class.forName("org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext");  
  10.      break;  
  11.     case REACTIVE:  
  12.      contextClass = Class.forName("org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext");  
  13.      break;  
  14.     default:  
  15.      contextClass = Class.forName("org.springframework.context.annotation.AnnotationConfigApplicationContext");  
  16.    }  
  17.   } catch (ClassNotFoundException var3) {  
  18.    throw new IllegalStateException("Unable create a default ApplicationContext, please specify an ApplicationContextClass", var3);  
  19.   }  
  20.  }  
  21.  return (ConfigurableApplicationContext)BeanUtils.instantiateClass(contextClass);  

這里會(huì)創(chuàng)建AnnotationConfigServletWebServerApplicationContext類(lèi)。而AnnotationConfigServletWebServerApplicationContext類(lèi)繼承了ServletWebServerApplicationContext,而這個(gè)類(lèi)是最終集成了AbstractApplicationContext。Java知音公眾號(hào)內(nèi)回復(fù)“后端面試”,送你一份Java面試題寶典

刷新上下文 

  1. //SpringApplication.java  
  2. //刷新上下文  
  3. private void refreshContext(ConfigurableApplicationContext context) {  
  4.  this.refresh(context);  
  5.  if (this.registerShutdownHook) {  
  6.   try {  
  7.    context.registerShutdownHook();  
  8.   } catch (AccessControlException var3) {  
  9.   }  
  10.  }  
  11.  
  12. //這里直接調(diào)用最終父類(lèi)AbstractApplicationContext.refresh()方法  
  13. protected void refresh(ApplicationContext applicationContext) {  
  14.  ((AbstractApplicationContext)applicationContext).refresh();  
  15.  
  1. //AbstractApplicationContext.java  
  2. public void refresh() throws BeansException, IllegalStateException {  
  3.  synchronized(this.startupShutdownMonitor) {  
  4.   this.prepareRefresh();  
  5.   ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();  
  6.   this.prepareBeanFactory(beanFactory);  
  7.   try {  
  8.    this.postProcessBeanFactory(beanFactory);  
  9.    this.invokeBeanFactoryPostProcessors(beanFactory);  
  10.    this.registerBeanPostProcessors(beanFactory);  
  11.    this.initMessageSource();  
  12.    this.initApplicationEventMulticaster();  
  13.    //調(diào)用各個(gè)子類(lèi)的onRefresh()方法,也就說(shuō)這里要回到子類(lèi):ServletWebServerApplicationContext,調(diào)用該類(lèi)的onRefresh()方法  
  14.    this.onRefresh();  
  15.    this.registerListeners();  
  16.    this.finishBeanFactoryInitialization(beanFactory);  
  17.    this.finishRefresh();  
  18.   } catch (BeansException var9) {  
  19.    this.destroyBeans();  
  20.    this.cancelRefresh(var9);  
  21.    throw var9;  
  22.   } finally {  
  23.    this.resetCommonCaches();  
  24.   }  
  25.  }  
  26.  
  1. //ServletWebServerApplicationContext.java  
  2. //在這個(gè)方法里看到了熟悉的面孔,this.createWebServer,神秘的面紗就要揭開(kāi)了。  
  3. protected void onRefresh() {  
  4.  super.onRefresh();  
  5.  try {  
  6.   this.createWebServer();  
  7.  } catch (Throwable var2) { 
  8.   }  
  9.  
  10. //ServletWebServerApplicationContext.java  
  11. //這里是創(chuàng)建webServer,但是還沒(méi)有啟動(dòng)tomcat,這里是通過(guò)ServletWebServerFactory創(chuàng)建,那么接著看下ServletWebServerFactory  
  12. private void createWebServer() {  
  13.  WebServer webServer = this.webServer;  
  14.  ServletContext servletContext = this.getServletContext();  
  15.  if (webServer == null && servletContext == null) {  
  16.   ServletWebServerFactory factory = this.getWebServerFactory();  
  17.   this.webServer = factory.getWebServer(new ServletContextInitializer[]{this.getSelfInitializer()});  
  18.  } else if (servletContext != null) {  
  19.   try {  
  20.    this.getSelfInitializer().onStartup(servletContext);  
  21.   } catch (ServletException var4) {  
  22.   }  
  23.  }  
  24.  this.initPropertySources();  
  25.  
  26. //接口  
  27. public interface ServletWebServerFactory {  
  28.     WebServer getWebServer(ServletContextInitializer... initializers);  
  29.  
  30. //實(shí)現(xiàn)  
  31. AbstractServletWebServerFactory  
  32. JettyServletWebServerFactory  
  33. TomcatServletWebServerFactory  
  34. UndertowServletWebServerFactory 

這里ServletWebServerFactory接口有4個(gè)實(shí)現(xiàn)類(lèi)

而其中我們常用的有兩個(gè):TomcatServletWebServerFactory和JettyServletWebServerFactory。 

  1. //TomcatServletWebServerFactory.java  
  2. //這里我們使用的tomcat,所以我們查看TomcatServletWebServerFactory。到這里總算是看到了tomcat的蹤跡。  
  3. @Override  
  4. public WebServer getWebServer(ServletContextInitializer... initializers) {  
  5.  Tomcat tomcat = new Tomcat(); 
  6.  File baseDir = (this.baseDirectory != null) ? this.baseDirectory : createTempDir("tomcat");  
  7.  tomcat.setBaseDir(baseDir.getAbsolutePath());  
  8.     //創(chuàng)建Connector對(duì)象  
  9.  Connector connector = new Connector(this.protocol);  
  10.  tomcat.getService().addConnector(connector); 
  11.  customizeConnector(connector);  
  12.  tomcat.setConnector(connector); 
  13.  tomcat.getHost().setAutoDeploy(false);  
  14.  configureEngine(tomcat.getEngine());  
  15.  for (Connector additionalConnector : this.additionalTomcatConnectors) {  
  16.   tomcat.getService().addConnector(additionalConnector);  
  17.  }  
  18.  prepareContext(tomcat.getHost(), initializers); 
  19.  return getTomcatWebServer(tomcat);  
  20.  
  21. protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {  
  22.  return new TomcatWebServer(tomcat, getPort() >= 0);  
  23.  
  24. //Tomcat.java  
  25. //返回Engine容器,看到這里,如果熟悉tomcat源碼的話(huà),對(duì)engine不會(huì)感到陌生。  
  26. public Engine getEngine() {  
  27.     Service service = getServer().findServices()[0];  
  28.     if (service.getContainer() != null) {  
  29.         return service.getContainer();  
  30.     }  
  31.     Engine engine = new StandardEngine();  
  32.     engine.setName( "Tomcat" );  
  33.     engine.setDefaultHost(hostname);  
  34.     engine.setRealm(createDefaultRealm());  
  35.     service.setContainer(engine);  
  36.     return engine;  
  37.  
  38. //Engine是最高級(jí)別容器,Host是Engine的子容器,Context是Host的子容器,Wrapper是Context的子容器 

getWebServer這個(gè)方法創(chuàng)建了Tomcat對(duì)象,并且做了兩件重要的事情:把Connector對(duì)象添加到tomcat中,configureEngine(tomcat.getEngine());

getWebServer方法返回的是TomcatWebServer。 

  1. //TomcatWebServer.java  
  2. //這里調(diào)用構(gòu)造函數(shù)實(shí)例化TomcatWebServer  
  3. public TomcatWebServer(Tomcat tomcat, boolean autoStart) {  
  4.  Assert.notNull(tomcat, "Tomcat Server must not be null");  
  5.  this.tomcat = tomcat;  
  6.  this.autoStart = autoStart;  
  7.  initialize();  
  8.  
  9. private void initialize() throws WebServerException {  
  10.     //在控制臺(tái)會(huì)看到這句日志  
  11.  logger.info("Tomcat initialized with port(s): " + getPortsDescription(false));  
  12.  synchronized (this.monitor) {  
  13.   try {  
  14.    addInstanceIdToEngineName();  
  15.    Context context = findContext();  
  16.    context.addLifecycleListener((event) -> {  
  17.     if (context.equals(event.getSource()) && Lifecycle.START_EVENT.equals(event.getType())) {  
  18.      removeServiceConnectors();  
  19.     }  
  20.    });  
  21.    //===啟動(dòng)tomcat服務(wù)===  
  22.    this.tomcat.start();  
  23.    rethrowDeferredStartupExceptions();  
  24.    try {  
  25.     ContextBindings.bindClassLoader(context, context.getNamingToken(), getClass().getClassLoader());  
  26.    }  
  27.    catch (NamingException ex) {              
  28.     }            
  29.             //開(kāi)啟阻塞非守護(hù)進(jìn)程  
  30.    startDaemonAwaitThread(); 
  31.   }  
  32.   catch (Exception ex) {  
  33.    stopSilently();  
  34.    destroySilently();  
  35.    throw new WebServerException("Unable to start embedded Tomcat", ex);  
  36.   }  
  37.  }  
  38.  
  1. //Tomcat.java  
  2. public void start() throws LifecycleException {  
  3.  getServer();  
  4.  server.start();  
  5.  
  6. //這里server.start又會(huì)回到TomcatWebServer的  
  7. public void stop() throws LifecycleException {  
  8.  getServer();  
  9.  server.stop();  
  10.  
  1. //TomcatWebServer.java  
  2. //啟動(dòng)tomcat服務(wù)  
  3. @Override  
  4. public void start() throws WebServerException {  
  5.  synchronized (this.monitor) {  
  6.   if (this.started) {  
  7.    return;  
  8.   }  
  9.   try {  
  10.    addPreviouslyRemovedConnectors();  
  11.    Connector connector = this.tomcat.getConnector();  
  12.    if (connector != null && this.autoStart) {  
  13.     performDeferredLoadOnStartup();  
  14.    }  
  15.    checkThatConnectorsHaveStarted();  
  16.    this.started = true 
  17.    //在控制臺(tái)打印這句日志,如果在yml設(shè)置了上下文,這里會(huì)打印  
  18.    logger.info("Tomcat started on port(s): " + getPortsDescription(true) + " with context path '"  
  19.      + getContextPath() + "'");  
  20.   }  
  21.   catch (ConnectorStartFailedException ex) {  
  22.    stopSilently();  
  23.    throw ex;  
  24.   }  
  25.   catch (Exception ex) {  
  26.    throw new WebServerException("Unable to start embedded Tomcat server", ex); 
  27.   }  
  28.   finally {  
  29.    Context context = findContext();  
  30.    ContextBindings.unbindClassLoader(context, context.getNamingToken(), getClass().getClassLoader());  
  31.   }  
  32.  }  
  33.  
  34. //關(guān)閉tomcat服務(wù)  
  35. @Override  
  36. public void stop() throws WebServerException {  
  37.  synchronized (this.monitor) {  
  38.   boolean wasStarted = this.started;  
  39.   try {  
  40.    this.started = false 
  41.    try {  
  42.     stopTomcat();  
  43.     this.tomcat.destroy();  
  44.    }  
  45.    catch (LifecycleException ex) {   
  46.     }  
  47.   }  
  48.   catch (Exception ex) {  
  49.    throw new WebServerException("Unable to stop embedded Tomcat", ex);  
  50.   }  
  51.   finally {  
  52.    if (wasStarted) {  
  53.     containerCounter.decrementAndGet();  
  54.    }  
  55.   }  
  56.  }  

附:tomcat頂層結(jié)構(gòu)圖

tomcat最頂層容器是Server,代表著整個(gè)服務(wù)器,一個(gè)Server包含多個(gè)Service。從上圖可以看除Service主要包括多個(gè)Connector和一個(gè)Container。Connector用來(lái)處理連接相關(guān)的事情,并提供Socket到Request和Response相關(guān)轉(zhuǎn)化。

Container用于封裝和管理Servlet,以及處理具體的Request請(qǐng)求。那么上文提到的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就可以對(duì)外提供服務(wù)了,但是Service要提供服務(wù)又必須提供一個(gè)宿主環(huán)境,那就非Server莫屬了,所以整個(gè)tomcat的聲明周期都由Server控制。

總結(jié)

SpringBoot的啟動(dòng)主要是通過(guò)實(shí)例化SpringApplication來(lái)啟動(dòng)的,啟動(dòng)過(guò)程主要做了以下幾件事情:配置屬性、獲取監(jiān)聽(tīng)器,發(fā)布應(yīng)用開(kāi)始啟動(dòng)事件初、始化輸入?yún)?shù)、配置環(huán)境,輸出banner、創(chuàng)建上下文、預(yù)處理上下文、刷新上下文、再刷新上下文、發(fā)布應(yīng)用已經(jīng)啟動(dòng)事件、發(fā)布應(yīng)用啟動(dòng)完成事件。

在SpringBoot中啟動(dòng)tomcat的工作在刷新上下這一步。而tomcat的啟動(dòng)主要是實(shí)例化兩個(gè)組件:Connector、Container,一個(gè)tomcat實(shí)例就是一個(gè)Server,一個(gè)Server包含多個(gè)Service,也就是多個(gè)應(yīng)用程序,每個(gè)Service包含多個(gè)Connector和一個(gè)Container,而一個(gè)Container下又包含多個(gè)子容器。 

 

責(zé)任編輯:龐桂玉 來(lái)源: Java知音
相關(guān)推薦

2021-01-11 15:02:27

Redis數(shù)據(jù)庫(kù)命令

2019-08-15 16:30:49

TomcatSpringBootJava

2023-06-30 07:51:44

springboot初始化邏輯

2021-09-01 09:32:40

工具

2010-08-29 21:09:57

DHCP協(xié)議

2019-06-18 15:57:25

HTTP緩存機(jī)制

2019-07-11 10:29:28

操作系統(tǒng)虛擬機(jī)Linux

2019-02-21 16:24:28

5G火車(chē)站設(shè)備

2023-05-10 08:29:28

Spring配置原理

2023-08-20 22:32:30

Spring容器錯(cuò)誤頁(yè)

2021-11-22 22:05:47

電腦回收站文件

2016-03-03 09:54:26

云環(huán)境后云時(shí)代

2014-06-25 09:11:48

技術(shù)

2022-12-08 08:40:25

大數(shù)據(jù)Hadoop存儲(chǔ)

2020-08-23 10:03:51

SynchronizeJava

2023-11-09 08:36:51

內(nèi)置工具類(lèi)Spring

2019-09-26 09:24:01

GC原理調(diào)優(yōu)

2020-05-13 08:10:32

HTTPS安全網(wǎng)站

2024-11-06 09:54:58

SpringJava開(kāi)發(fā)

2021-04-26 17:23:21

JavaCAS原理
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)