关于java:4SpringBoot嵌入式Servlet容器

4次阅读

共计 2092 个字符,预计需要花费 6 分钟才能阅读完成。

1、切换嵌入式 Servlet 容器

  • 默认反对的 web 服务器 webServer:
 Tomcat, Jetty,  Undertow
 ServletWebServerApplicationContext 容器启动寻找 ServletWebServerFactory 并疏导创立服务器
  • 切换服务器(能够切换四种)

    切换的形式:<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>  导入
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-undertow</artifactId>
          </dependency>
              
              
    2022-07-17 19:34:02.650  INFO 6808 --- [restartedMain] o.s.b.w.e.undertow.UndertowWebServer     : Undertow started on port(s) 8080 (http)

原理

  • SpringBoot 利用启动发现以后是 Web 利用。因为导了 web 场景包,它外面也导入 tomcat
  • web 利用会创立一个 web 版的 ioc 容器,名字叫 ServletWebServerApplicationContext
  • ServletWebServerApplicationContext 它在我的项目一启动的时候寻找 ServletWebServerFactory(Servlet 的 web 服务器工厂 —> 这个工厂生产 Servlet 的 web 服务器)
  • SpringBoot 底层默认有很多的 WebServer 工厂:TomcatServletWebServerFactory, JettyServletWebServerFactory, UndertowServletWebServerFactory
  • 这些 web 服务器工厂不须要咱们配,底层间接会有一个主动配置类ServletWebServerFactoryAutoConfiguration
  • ServletWebServerFactoryAutoConfiguration导入了ServletWebServerFactoryConfiguration(配置类)
  • ServletWebServerFactoryConfiguration 配置类 依据动静判断零碎中到底导入了哪个 Web 服务器的包。(默认是 web-starter 导入 tomcat 包),容器中就有 TomcatServletWebServerFactory
  • TomcatServletWebServerFactory 创立出 Tomcat 服务器 TomcatWebServer 并启动;TomcatWebServer 的结构器领有初始化办法 initialize,这个初始化办法把所有货色筹备好,把 tomcat 调用 start 办法this.tomcat.start(); 启动 tomcat
  • 其实内嵌服务器,就是手动把启动服务器的代码调用(前提是 tomcat 外围 jar 包存在,能力启动 tomcat)

2、定制 Servlet 容器

  • 实现 WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>
    ○ 把配置文件的值和 ServletWebServerFactory 进行绑定
  • 批改配置文件 server.xxx
  • 间接自定义 ConfigurableServletWebServerFactory

xxxxxCustomizer:定制化器,能够扭转 xxxx 的默认规定

import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.stereotype.Component;

@Component
public class CustomizationBean implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {

    @Override
    public void customize(ConfigurableServletWebServerFactory server) {server.setPort(9000);
    }

}
正文完
 0