总在说SpringBoot内置了tomcat启动,那它的原理你说的清楚吗?

开发 后端
不得不说SpringBoot的开发者是在为大众程序猿谋福利,把大家都惯成了懒汉,xml不配置了,连tomcat也懒的配置了,典型的一键启动系统,那么tomcat在springboot是怎么启动的呢?来看看吧。

前言

不得不说SpringBoot的开发者是在为大众程序猿谋福利,把大家都惯成了懒汉,xml不配置了,连tomcat也懒的配置了,典型的一键启动系统,那么tomcat在springboot是怎么启动的呢?

内置tomcat

开发阶段对我们来说使用内置的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函数入口,两句代码最耀眼,分别是SpringBootApplication注解和SpringApplication.run()方法。

发布生产

发布的时候,目前大多数的做法还是排除内置的tomcat,打瓦包(war)然后部署在生产的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函数,主要是继承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函数说起 

  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.   //创建应用上下文  
  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方法中,重点关注创建应用上下文(createApplicationContext)和刷新上下文(refreshContext)。

创建上下文 

  1. //创建上下文  
  2. protected ConfigurableApplicationContext createApplicationContext() {  
  3.  Class<?> contextClass = this.applicationContextClass;  
  4.  if (contextClass == null) {  
  5.   try {  
  6.    switch(this.webApplicationType) {  
  7.     case SERVLET:  
  8.                     //创建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);  

这里会创建AnnotationConfigServletWebServerApplicationContext类。而AnnotationConfigServletWebServerApplicationContext类继承了ServletWebServerApplicationContext,而这个类是最终集成了AbstractApplicationContext。Java知音公众号内回复“后端面试”,送你一份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. //这里直接调用最终父类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.    //调用各个子类的onRefresh()方法,也就说这里要回到子类:ServletWebServerApplicationContext,调用该类的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. //这里是创建webServer,但是还没有启动tomcat,这里是通过ServletWebServerFactory创建,那么接着看下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. //实现  
  31. AbstractServletWebServerFactory  
  32. JettyServletWebServerFactory  
  33. TomcatServletWebServerFactory  
  34. UndertowServletWebServerFactory 

这里ServletWebServerFactory接口有4个实现类

而其中我们常用的有两个: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.     //创建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这个方法创建了Tomcat对象,并且做了两件重要的事情:把Connector对象添加到tomcat中,configureEngine(tomcat.getEngine());

getWebServer方法返回的是TomcatWebServer。 

  1. //TomcatWebServer.java  
  2. //这里调用构造函数实例化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. //关闭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顶层结构图

tomcat最顶层容器是Server,代表着整个服务器,一个Server包含多个Service。从上图可以看除Service主要包括多个Connector和一个Container。Connector用来处理连接相关的事情,并提供Socket到Request和Response相关转化。

Container用于封装和管理Servlet,以及处理具体的Request请求。那么上文提到的Engine>Host>Context>Wrapper容器又是怎么回事呢?我们来看下图:

综上所述,一个tomcat只包含一个Server,一个Server可以包含多个Service,一个Service只有一个Container,但有多个Connector,这样一个服务可以处理多个连接。

多个Connector和一个Container就形成了一个Service,有了Service就可以对外提供服务了,但是Service要提供服务又必须提供一个宿主环境,那就非Server莫属了,所以整个tomcat的声明周期都由Server控制。

总结

SpringBoot的启动主要是通过实例化SpringApplication来启动的,启动过程主要做了以下几件事情:配置属性、获取监听器,发布应用开始启动事件初、始化输入参数、配置环境,输出banner、创建上下文、预处理上下文、刷新上下文、再刷新上下文、发布应用已经启动事件、发布应用启动完成事件。

在SpringBoot中启动tomcat的工作在刷新上下这一步。而tomcat的启动主要是实例化两个组件:Connector、Container,一个tomcat实例就是一个Server,一个Server包含多个Service,也就是多个应用程序,每个Service包含多个Connector和一个Container,而一个Container下又包含多个子容器。 

 

责任编辑:庞桂玉 来源: Java知音
相关推荐

2019-08-15 16:30:49

TomcatSpringBootJava

2021-01-11 15:02:27

Redis数据库命令

2023-06-30 07:51:44

springboot初始化逻辑

2021-09-01 09:32:40

工具

2019-02-21 16:24:28

5G火车站设备

2010-08-29 21:09:57

DHCP协议

2019-06-18 15:57:25

HTTP缓存机制

2019-07-11 10:29:28

操作系统虚拟机Linux

2023-05-10 08:29:28

Spring配置原理

2023-08-20 22:32:30

Spring容器错误页

2016-03-03 09:54:26

云环境后云时代

2021-11-22 22:05:47

电脑回收站文件

2023-11-09 08:36:51

内置工具类Spring

2019-09-26 09:24:01

GC原理调优

2022-12-08 08:40:25

大数据Hadoop存储

2020-08-23 10:03:51

SynchronizeJava

2020-05-13 08:10:32

HTTPS安全网站

2014-06-25 09:11:48

技术

2020-02-13 17:49:55

SpringBoot放弃选择

2022-06-14 11:01:48

SpringBootTomcatUndertow
点赞
收藏

51CTO技术栈公众号