Springboot内置Tomcat原理

article/2025/9/14 0:34:46
  • SpringBoot的启动主要是通过实例化SpringApplication来启动的,启动过程主要做了以下几件事情:配置属性、获取监听器,发布应用开始启动事件初、始化输入参数、配置环境,输出banner、创建上下文、预处理上下文、刷新上下文、再刷新上下文、发布应用已经启动事件、发布应用启动完成事件。
  • 在SpringBoot中启动tomcat的工作在刷新上下这一步。而tomcat的启动主要是实例化两个组件:Connector、Container,一个tomcat实例就是一个Server,一个Server包含多个Service,也就是多个应用程序,每个Service包含多个Connector和一个Container,而一个Container下又包含多个子容器。

 

内置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控制。

 


http://chatgpt.dhexx.cn/article/FPofFs2g.shtml

相关文章

【springboot】自动整合Tomcat原理

通过前面我们会SpringBoot的自动配置机制、Starter机制、启动过程的底层分析&#xff0c;我们拿一个实际的业务案例来串讲一下&#xff0c;那就是SpringBoot和Tomcat的整合。 我们知道&#xff0c;只要我们的项目添加的starter为&#xff1a;spring-boot-starter-web&#xff…

总结:SpringBoot内嵌Tomcat原理

一、介绍 一般我们启动web服务都需要单独的去安装tomcat&#xff0c;而Springboot自身却直接整合了Tomcat&#xff0c;什么原理呢&#xff1f; 二、原理 SpringBoot应用只需要引入spring-boot-starter-web中这个依赖&#xff0c;应用程序就默认引入了tomcat依赖&#xff0c;其…

Tomcat的架构原理

一、前言 Tomcat服务器是一个开源的轻量级Web应用服务器&#xff0c;在中小型系统和并发量小的场合下被普遍使用&#xff0c;是开发和调试Servlet、JSP程序的首选。同时它是运行在JVM中的一个进程&#xff0c;包含Web容器&#xff0c;相当于是Web容器和JVM之间的中间件。 二、…

浅析tomcat原理

浅析tomcat原理 上上个星期&#xff0c;看了一下how tomcat works这本书&#xff0c;今天捡起来看一会&#xff0c;发现忘得有点快&#xff0c;特地写点东西&#xff0c;加深一下记忆。因为书讲的是tomcat4&#xff0c;5的内容&#xff0c;比较旧了&#xff0c;所以和最新的to…

Tomcat底层原理

一、Tomcat启动时到底对我们的应用程序做了什么&#xff1f; 当我们把一个应用程序的war包放到Tomcat的webapps目录后&#xff0c;启动Tomcat&#xff0c;然后就可以通过浏览器发送Http请求访问该war包内的Servlet了。 这个过程包括&#xff1a; 1、启动Tomcat 2、Tomcat处理H…

tomcat的工作原理以及简介

Tomcat简介 Tomcat是一个JSP/Servlet容器。其作为Servlet容器&#xff0c;有三种工作模式&#xff1a;独立的Servlet容器、进程内的Servlet容器和进程外的Servlet容器&#xff0c; 1.Tomcat是运行在JVM中的一个进程。它定义为【中间件】&#xff0c;顾名思义&#xff0c;是一个…

tomcat组成及工作原理

1 - Tomcat Server的组成部分 1.1 - Server A Server element represents the entire Catalina servlet container. (Singleton) 1.2 - Service A Service element represents the combination of one or more Connector components that share a single Engine Servic…

Tomcat工作原理介绍

Web应用程序都是靠Web服务器运行的&#xff0c;Tomcat是常用的Web服务器(兼具Servlet容器HTTP服务器功能)之一&#xff0c;此篇博客将从工作原理上来认识Tomcat。Tomcat作为Web服务器需要处理两类核心任务&#xff1a;处理 Socket 连接&#xff0c;负责网络字节流与Request和Re…

tomcat原理解析(一):一个简单的实现

一 概述 前段时间去面试&#xff0c;被人问到了tomcat实现原理。由于平时没怎么关注容器的实现细节&#xff0c;这个问题基本没回答上来。所以最近花了很多时间一直在网上找资料和看tomcat的源码来研究里面处理一个HTTP请求的流程。网上讲tomcat的帖子比较多&#xff0c;大多都…

Tomcat工作原理之运行机制

一、Tomcat运行原理分析1.Tomcat是运行在JVM中的一个进程。它定义为【中间件】&#xff0c;顾名思义&#xff0c;是一个在Java项目与JVM之间的中间容器。 2.Web项目的本质&#xff0c;是一大堆的资源文件和方法。Web项目没有入口方法(main方法)&#xff0c;&#xff0c;意味着…

tomcat 工作原理

大致的架构是 jsptomcatmysql&#xff0c;记录tomcat学习一点笔记。 Tomcat是Servlet运行环境&#xff08;容器&#xff09;&#xff0c;每个servlet执行init(),service(),destory() 以下是servlet的作用 Servlet的调用 Tomcat的工作模式3种&#xff1a;独立Servlet&#xff0c…

Tomcat的原理及架构

转自&#xff1a;https://zhuanlan.zhihu.com/p/35398064 俗话说&#xff0c;站在巨人的肩膀上看世界&#xff0c;一般学习的时候也是先总览一下整体&#xff0c;然后逐个部分个个击破&#xff0c;最后形成思路&#xff0c;了解具体细节&#xff0c;Tomcat的结构很复杂&#xf…

Tomcat基本原理

1.Tomcat核心&#xff1a; Http服务器Servlet容器 组件分工&#xff1a; 连接器Connector&#xff1a;处理 Socket 连接&#xff0c;负责网络字节流与 Request 和 Response 对象的转化。容器Container&#xff1a;加载和管理 Servlet&#xff0c;以及具体处理 Request 请求。 …

tomcat的工作原理

本文源自转载&#xff1a;你还记得 Tomcat 的工作原理么 一、Tomcat 整体架构 Tomcat 是一个免费的、开源的、轻量级的 Web 应用服务器。适合在并发量不是很高的中小企业项目中使用。 二、文件目录结构 以下是 Tomcat 8 主要目录结构 三、功能组件结构 Tomcat 的核心功能有…

Tomcat原理整理

目录接口 功能组件 Tomcat 的核心功能有两个&#xff0c;分别是负责接收和反馈外部请求的连接器 Connector&#xff0c;和负责处理请求的容器 Container。其中连接器和容器相辅相成&#xff0c;多个 Connector 和一个 Container 一起构成了基本的 web 服务 Service。每个 Serve…

Tomcat工作原理详细介绍

大部分企业的 Web 应用都运行在它上面&#xff0c;Tomcat 对于程序员来说算是老朋友了&#xff0c;那么今天带大家走近这位老朋友&#xff0c;看看它是如何处理 Web 请求&#xff0c;以及它内部的体系结构&#xff0c;这对帮助我们理解 Tomcat 的使用大有益处。 本文你将会学会…

Tomcat原理

Tomcat顶层架构 Tomcat的顶层结构图&#xff1a; 1、Tomcat中最顶层的容器是Server&#xff0c;代表着整个服务器&#xff0c;一个Server可以包含至少一个Service&#xff0c;用于具体提供服务。 2、Service主要包含两个部分&#xff1a;Connector和Container。 Tomcat 的心脏…

javascript 文本框限制输入1到10位数字正则表达式

<meta http-equiv"Content-Type" content"text/html; charsetUTF-8"> <!DOCTYPE html> <html> <head><title>DOM 教程</title><style></style><!--不需要再次引用jquery--><script type"te…

js数字正则

js正则表达式 1.了解什么是正则表达式&#xff1f; 正则表达式&#xff08;Regular Expression&#xff09;又称规则表达式&#xff0c;简单来说它就是一个概念&#xff0c;用事先声明好的字符和字符的组合&#xff0c;来组成一个“规则字符串”&#xff0c;用来检测我们书写…

卷积神经网络降维方法,深度神经网络降维方法

1、卷积神经网络中用1*1 卷积有什么作用或者好处 1*1卷积的主要作用有以下几点&#xff1a; 1、降维&#xff08; dimension reductionality &#xff09;。比如&#xff0c;一张500 * 500且厚度depth为100 的图片在20个filter上做1*1的卷积&#xff0c;那么结果的大小为500*5…