SpringBoot内置Tomcat
Tomcat组成
https://juejin.im/post/5a82a1d05188257a5a4cb418
内置Tomcat
SpringBoot使用的就是内置Tomcat,利用Tomcat这个类来构建Tomcat服务
public EmbeddedServletContainer getEmbeddedServletContainer(
ServletContextInitializer... initializers) {
Tomcat tomcat = new Tomcat();
File baseDir = (this.baseDirectory != null ? this.baseDirectory
: createTempDir("tomcat"));
tomcat.setBaseDir(baseDir.getAbsolutePath());
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 getTomcatEmbeddedServletContainer(tomcat);
}
在该方法中,利用Tomcat这个类,对Tomcat组件进行了默认的初始化,对Connector
进行了定制
protected void customizeConnector(Connector connector) {
int port = (getPort() >= 0 ? getPort() : 0);
connector.setPort(port);
if (StringUtils.hasText(this.getServerHeader())) {
connector.setAttribute("server", this.getServerHeader());
}
if (connector.getProtocolHandler() instanceof AbstractProtocol) {
customizeProtocol((AbstractProtocol<?>) connector.getProtocolHandler());
}
if (getUriEncoding() != null) {
connector.setURIEncoding(getUriEncoding().name());
}
// If ApplicationContext is slow to start we want Tomcat not to bind to the socket
// prematurely...
connector.setProperty("bindOnInit", "false");
if (getSsl() != null && getSsl().isEnabled()) {
customizeSsl(connector);
}
if (getCompression() != null && getCompression().getEnabled()) {
customizeCompression(connector);
}
for (TomcatConnectorCustomizer customizer : this.tomcatConnectorCustomizers) {
customizer.customize(connector);
}
}
在该方法中调用了一系列TomcatConnectorCustomizer
对Connector
进行设置,TomcatConnectorCustomizer
实例都是在ServerProperties
中添加的,同时在ServerProperties
对tomcat的其他属性也进行了设置
DispatcherServlet
的注册是依靠DispatcherServletAutoConfiguration
自动配置生成的ServletRegistrationBean
进行注册的,在StandardContext
中startInternal
方法中,利用TomcatStarter
类进行了注册
如果需要注册额外的Servlet、Listener、Filter只需要创建下面相应类的bean就行 ServletRegistrationBean ServletListenerRegistrationBean FilterRegistrationBean
Tomcat后台线程的创建
https://mp.weixin.qq.com/s/ATtQVYhGkAkY5Hx0cGUC6g