SpringBoot嵌入式Web容器原理与使用介绍

2022-10-20 16:30:48

目录原理应用1.切换Web服务器2.定制服务器规则嵌入式Web容器:应用中内置服务器(Tomcat),不用在外部配置服务器了原理SpringBoot项目启动,发现是web应用,引入we...

目录
原理
应用
1. 切换Web服务器
2. 定制服务器规则

嵌入式 Web 容器:应用中内置服务器(Tomcat),不用在外部配置服务器了

原理

SpringBoot 项目启动,发现是 web 应用,引入 web 场景包 ----- 如:Tomcat
web 应用创建一个 web 版的 IOC 容器 ServletWebServerApplicationContext
ServletWebServerApplicationContext 启动的时候寻找 ServletWebServerFactory (Servlet 的 web 服务器工厂,用于生产 Servlet 服务器)
ServletWebServerFactory 底层默认有很多 Web 服务器工厂

SpringBoot嵌入式Web容器原理与使用介绍

底层会自动配置好 ,自动配置类 ServletWebServerFactoryAutoConfiguration
ServletWebServerFactoryAutoConfiguration 导入 ServletWebServerFactoryConfiguration 工厂配置类

ServletWebServerFactoryConfiguration.class

SpringBoot嵌入式Web容器原理与使用介绍

动态判断系统中导入了那个web服务器配置包
如果导入 Tomcat 依赖,会自动放一个 Tomcat 服务器工厂, TomcatServletWebServerFactory 为我们创建出 Tomcat 服务器工厂
Tomcat 底层支持如下服务器

SpringBoot嵌入式Web容器原理与使用介绍

@Override
public WebServer getWebServer(ServletContextInitializer... initializers) {
if (this.disableMBeanRegistry) {
Registry.disableRegistry();
}
Tomcat tomcat = new Tomcat();
File baseDir = (this.baseDirectory != null) ? this.baseDirectory : createTempDir("tomcat");
tomcat.setBaseDir(baseDir.getAbsolutePath());
Connector connector = new Connector(this.protocol);
connector.setThrowOnFailure(true);
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);
}

总结: 所谓内嵌服务器,就是把我们手动启动服务器的方法放进框架中了。

应用

1. 切换Web服务器

排除 tomcat 服务器,导入 undertow 依赖

       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
  php          <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-undertow</artifactId>
        </dependency>

2. 定制服务器规则

方法一: 修改 server 下的配置文件

ServerProperties.class

SpringBoot嵌入式Web容器原理与使用介绍

server.undertow.Accesslog.dir=/tmp

方法二: 自定义 ConfigurableServletWebServerFactory

方法三: 自定义 ServletWebServerFactoryCustomizer 定制化器

作用: 将配置文件的值,与 ServletWebServerFactory 绑定

SpringBoot 设计: Customizer 定制化器,可以定制 XXX 规则

到此这篇关于SpringBoot嵌入式Web容器原理与使用介绍的文章就介绍到这了,更多相关SpringBoot嵌入式Web容器内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!