成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

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

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

前言

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

內(nèi)置tomcat

開發(fā)階段對我們來說使用內(nèi)置的tomcat是非常夠用了,當然也可以使用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("===應用啟動耗時:"+(System.currentTimeMillis()-time)+"===");  
  7.     }  

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

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

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

  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依賴--->  
  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,并重寫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("===應用啟動耗時:"+(System.currentTimeMillis()-time)+"===");  
  7.     } 
  8.     @Override  
  9.     protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {  
  10.         return builder.sources(this.getClass());  
  11.     }  

從main函數(shù)說起 

  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,這里你可以自己涂鴉一下,換成自己項目的logo  
  13.   Banner printedBanner = this.printBanner(environment);   
  14.   //創(chuàng)建應用上下文  
  15.   context = this.createApplicationContext();  
  16.   exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);  
  17.   //預處理上下文  
  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中是怎么啟動的,那么run方法中,重點關(guān)注創(chuà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);  

這里會創(chuàng)建AnnotationConfigServletWebServerApplicationContext類。而AnnotationConfigServletWebServerApplicationContext類繼承了ServletWebServerApplicationContext,而這個類是最終集成了AbstractApplicationContext。Java知音公眾號內(nèi)回復“后端面試”,送你一份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)用最終父類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)用各個子類的onRefresh()方法,也就說這里要回到子類:ServletWebServerApplicationContext,調(diào)用該類的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. //在這個方法里看到了熟悉的面孔,this.createWebServer,神秘的面紗就要揭開了。  
  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,但是還沒有啟動tomcat,這里是通過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. //實現(xiàn)  
  31. AbstractServletWebServerFactory  
  32. JettyServletWebServerFactory  
  33. TomcatServletWebServerFactory  
  34. UndertowServletWebServerFactory 

這里ServletWebServerFactory接口有4個實現(xiàn)類

而其中我們常用的有兩個: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對象  
  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源碼的話,對engine不會感到陌生。  
  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是最高級別容器,Host是Engine的子容器,Context是Host的子容器,Wrapper是Context的子容器 

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

getWebServer方法返回的是TomcatWebServer。 

  1. //TomcatWebServer.java  
  2. //這里調(diào)用構(gòu)造函數(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.     //在控制臺會看到這句日志  
  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.    //===啟動tomcat服務===  
  22.    this.tomcat.start();  
  23.    rethrowDeferredStartupExceptions();  
  24.    try {  
  25.     ContextBindings.bindClassLoader(context, context.getNamingToken(), getClass().getClassLoader());  
  26.    }  
  27.    catch (NamingException ex) {              
  28.     }            
  29.             //開啟阻塞非守護進程  
  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又會回到TomcatWebServer的  
  7. public void stop() throws LifecycleException {  
  8.  getServer();  
  9.  server.stop();  
  10.  
  1. //TomcatWebServer.java  
  2. //啟動tomcat服務  
  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.    //在控制臺打印這句日志,如果在yml設置了上下文,這里會打印  
  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服務  
  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,代表著整個服務器,一個Server包含多個Service。從上圖可以看除Service主要包括多個Connector和一個Container。Connector用來處理連接相關(guān)的事情,并提供Socket到Request和Response相關(guān)轉(zhuǎn)化。

Container用于封裝和管理Servlet,以及處理具體的Request請求。那么上文提到的Engine>Host>Context>Wrapper容器又是怎么回事呢?我們來看下圖:

綜上所述,一個tomcat只包含一個Server,一個Server可以包含多個Service,一個Service只有一個Container,但有多個Connector,這樣一個服務可以處理多個連接。

多個Connector和一個Container就形成了一個Service,有了Service就可以對外提供服務了,但是Service要提供服務又必須提供一個宿主環(huán)境,那就非Server莫屬了,所以整個tomcat的聲明周期都由Server控制。

總結(jié)

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

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

 

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

2021-01-11 15:02:27

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

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-07-11 10:29:28

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

2019-02-21 16:24:28

5G火車站設備

2019-06-18 15:57:25

HTTP緩存機制

2023-08-20 22:32:30

Spring容器錯誤頁

2023-05-10 08:29:28

Spring配置原理

2021-11-22 22:05:47

電腦回收站文件

2016-03-03 09:54:26

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

2014-06-25 09:11:48

技術(shù)

2022-12-08 08:40:25

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

2019-09-26 09:24:01

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

2020-08-23 10:03:51

SynchronizeJava

2023-11-09 08:36:51

內(nèi)置工具類Spring

2020-05-13 08:10:32

HTTPS安全網(wǎng)站

2021-04-26 17:23:21

JavaCAS原理

2019-09-03 09:19:34

CPU架構(gòu)內(nèi)核
點贊
收藏

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

主站蜘蛛池模板: 欧美日韩国产一区二区三区 | 97精品国产97久久久久久免费 | 日韩欧美国产精品 | 国外成人在线视频 | 精品日韩 | 欧美精品一区二区在线观看 | 亚洲免费视频网站 | 久久综合久色欧美综合狠狠 | 亚洲精品1 | 午夜成人在线视频 | 久久久久国产一区二区三区四区 | 97av视频在线观看 | 亚洲天堂免费在线 | 国产精品美女久久久av超清 | 国产高清一区二区三区 | 亚洲国产成人精品久久久国产成人一区 | 日韩视频一区二区三区 | 久久成人高清视频 | 精品国产色 | 亚洲精品一区二区三区蜜桃久 | 日日噜噜噜夜夜爽爽狠狠视频97 | 亚洲黄色网址视频 | 国产午夜在线观看 | 91精品国产91久久综合桃花 | 亚洲国产成人av好男人在线观看 | www操操| 欧美日韩专区 | 欧美在线视频网 | 国产精品自产av一区二区三区 | 亚洲精品乱码久久久久v最新版 | 亚洲一区二区三区免费观看 | 91精品一区二区三区久久久久久 | 欧美久久影院 | 亚洲欧美日韩精品久久亚洲区 | 看一级毛片视频 | 国产精品欧美大片 | 欧美日韩一 | 欧美爱爱视频网站 | 欧美日韩成人影院 | 国产高清视频一区二区 | www.免费看片.com|