前言

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

内置tomcat

开发阶段对我们来说使用内置的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("===应用启动耗时:"+(System.currentTimeMillis()-time)+"===");}
}

这里是main函数入口,两句代码最耀眼,分别是SpringBootApplication注解和SpringApplication.run()方法。

发布生产

发布的时候,目前大多数的做法还是排除内置的tomcat,打瓦包(war)然后部署在生产的tomcat中,好吧,那打包的时候应该怎么处理?

<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依赖--->
<dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version><scope>provided</scope>
</dependency>

更新main函数,主要是继承SpringBootServletInitializer,并重写configure()方法。

@SpringBootApplication
public class MySpringbootTomcatStarter extends SpringBootServletInitializer {public static void main(String[] args) {Long time=System.currentTimeMillis();SpringApplication.run(MySpringbootTomcatStarter.class);System.out.println("===应用启动耗时:"+(System.currentTimeMillis()-time)+"===");}@Overrideprotected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {return builder.sources(this.getClass());}
}

从main函数说起

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,这里你可以自己涂鸦一下,换成自己项目的logoBanner printedBanner = this.printBanner(environment);//创建应用上下文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中是怎么启动的,那么run方法中,重点关注创建应用上下文(createApplicationContext)和刷新上下文(refreshContext)。

创建上下文

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

这里会创建AnnotationConfigServletWebServerApplicationContext类。 而AnnotationConfigServletWebServerApplicationContext类继承了ServletWebServerApplicationContext,而这个类是最终集成了AbstractApplicationContext。

刷新上下文

//SpringApplication.java
//刷新上下文
private void refreshContext(ConfigurableApplicationContext context) {this.refresh(context);if (this.registerShutdownHook) {try {context.registerShutdownHook();} catch (AccessControlException var3) {}}
}//这里直接调用最终父类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();//调用各个子类的onRefresh()方法,也就说这里要回到子类:ServletWebServerApplicationContext,调用该类的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
//在这个方法里看到了熟悉的面孔,this.createWebServer,神秘的面纱就要揭开了。
protected void onRefresh() {super.onRefresh();try {this.createWebServer();} catch (Throwable var2) {}
}//ServletWebServerApplicationContext.java
//这里是创建webServer,但是还没有启动tomcat,这里是通过ServletWebServerFactory创建,那么接着看下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);
}//实现
AbstractServletWebServerFactory
JettyServletWebServerFactory
TomcatServletWebServerFactory
UndertowServletWebServerFactory

这里ServletWebServerFactory接口有4个实现类

而其中我们常用的有两个: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());//创建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源码的话,对engine不会感到陌生。
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这个方法创建了Tomcat对象,并且做了两件重要的事情:把Connector对象添加到tomcat中,configureEngine(tomcat.getEngine()); getWebServer方法返回的是TomcatWebServer。

//TomcatWebServer.java
//这里调用构造函数实例化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 {//在控制台会看到这句日志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();}});//===启动tomcat服务===this.tomcat.start();rethrowDeferredStartupExceptions();try {ContextBindings.bindClassLoader(context, context.getNamingToken(), getClass().getClassLoader());}catch (NamingException ex) {}//开启阻塞非守护进程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又会回到TomcatWebServer的
public void stop() throws LifecycleException {getServer();server.stop();
}

//TomcatWebServer.java
//启动tomcat服务
@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设置了上下文,这里会打印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());}}
}//关闭tomcat服务
@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,代表着整个服务器,一个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下又包含多个子容器。

tomcat怎么平滑更新项目_SpringBoot内置tomcat启动原理相关推荐

  1. 访问tomcat服务器文件路径,外置tomcat映射服务器路径以及springboot内置tomcat映射路径配置...

    外置tomcat映射路径 在tomcat里的conf下的server.xml里Host标签下加入 其中的docBase就是磁盘映射路径,path为访问路径,比如localhost:8080/repor ...

  2. tomcat服务器文件被清空,SpringBoot内置Tomcat缓存文件目录被意外删除导致异常

    在项目中,一般会将文件临时保存到缓存目录 当时使用 File.createTempFile("tmp", ext, (File) request.getServletContext ...

  3. tomcat怎么平滑更新项目_tomcat_deploy 平滑启动脚本

    1 #!/bin/bash2 cat < 4 +-------------------------------------------------------------+ 5 A)服务器192 ...

  4. windows查看tomcat连接数_Springboot内置Tomcat线程数优化

    # 等待队列长度,默认100.队列也做缓冲池用,但也不能无限长,不但消耗内存,而且出队入队也消耗CPU server.tomcat.accept-count=1000 # 最大工作线程数,默认200. ...

  5. 项目部署—移除Spring Boot内置Tomcat,部署到云服务器Tomcat

        以往部署Java web项目到阿里云服务器时,直接将项目打包成war包,放到阿里云服务器中tomcat的webapps目录下,就可以访问了.   SpringBoot默认给我们提供了内置tom ...

  6. Spring Boot 内置Tomcat——IntelliJ IDEA中配置模块目录设为文档根目录(DocumentRoot)解决方案

    源码分析 org.springframework.boot.web.servlet.server.DocumentRoot /*** Returns the absolute document roo ...

  7. SpringBoot整合DWR-3.0.2-RELEASE版本,以及解决项目在开发环境及其外置Tomcat运行正常,独立JAR形式内置Tomcat运行异常的问题

    SpringBoot整合DWR 3.0.2-RELEASE填坑日记 填坑背景 问题溯源 填坑步骤 一.示例代码结构 二.示例代码说明 1.框架配置代码编写 2.后端服务代码编写 3.后端服务注册配置 ...

  8. springBoot项目打jar包发布时启动包内置tomcat无法启动错误分析

    环境:jdk1.7.sqlserver数据库.   框架:springboot  + mybatis+freemark .工具:eclipse.maven.svn 最近在做一个项目接近尾声,帮同事进行 ...

  9. SpringBoot内置Tomcat浅析

    一.SpringBoot框架内置Tomcat,开发非常方便,随着SpringBoot的框架升级,内置Tomcat也更新版本.本文SpringBoot框架版本:2.2.10. 1.如何查看SpringB ...

最新文章

  1. ReSimNet: drug response similarity prediction using Siamese neural networks
  2. Android应用程序键盘(Keyboard)消息处理机制分析(20)
  3. 案发设计与分析 试验一
  4. python 爬虫源代码-从零开始学Python网络爬虫_源代码.rar
  5. Python3 注释
  6. django07: 模板语言(旧笔记)
  7. c语言c1变成e并输出,【图片】(原创)用纯C变了个变色输出字符的程序。。。【c语言吧】_百度贴吧...
  8. Php点击更换封面,JavaScript_js实现点击图片改变页面背景图的方法,本文实例讲述了js实现点击图 - phpStudy...
  9. Spring boot web开发实战
  10. MySQL数据库基础(三)——SQL语言
  11. CHR-6dm datasheet 中文翻译
  12. printf() 输出控制符
  13. 最简单的使用nginx实现动静分离
  14. Linux时间同步(NTP)
  15. 我们不应该歧视任何的编程语言,因为他们都是萌娘
  16. 测试听力口语软件,上、英语系学姐最全整理的34个英语学习App 针对听力、口语、阅读...
  17. 企业邮箱域名怎么选?公司邮箱格式怎么写?
  18. 浏览器/html/css面试题
  19. html页边距为负值,css中的padding属性可以为负值吗?css中padding属性的详解
  20. imac打开terminal终端器

热门文章

  1. REDIS的几个测试结果
  2. 用户态线程在AI中的应用
  3. python从右向左第三个_Python字符串操作,通过查找右括号到左括号来删除内容
  4. hibernate mysql 设置时区_Hibernate连接MYSQL失败提示时区错误该怎么解决?
  5. linux i查看o性能度量,11.9.18 学习笔记:性能管理
  6. 华为创造出5g和鸿蒙,拥有5G专利,开发鸿蒙系统:《华为智慧》复盘成长路总结成功之道...
  7. linux qt wifi连接,贡献自己写的,在linux,arm下的屏幕搜索wifi并连接(qt,多选择,wifi按信号排列)...
  8. android 获取网卡mac_在Android机顶盒上 怎么样获取有线网卡MAC地址?
  9. php 格式化评论量函数,深入剖析PHP中printf()函数格式化使用
  10. 对于七段数码数字模型进行改进:一个关键的数字1的问题