从此
文章
📄文章 #️⃣专题 🌐上网 📺 🛒 📱

SpringBoot 内嵌 Web Server 容器的解析

🕗2023-06-26

今天给大家分享一个SpringBoot的内嵌Web容器,在SpringBoot还没有出现时,我们使用Java开发了Web项目,需要将其部署到Tomcat下面,需要配置很多xml文件,SpringBoot出现后,就从繁琐的xml文件中解脱出来了,SpringBoot将Web容器进行了内嵌,我们只需要将项目打成一个jar包,就可以运行了,大大省略了开发成本,那么SpringBoot是怎么实现的呢,我们今天就来详细介绍。

SpringBoot提供的内嵌容器

SpringBoot提供了四种Web容器,分别为Tomcat,Jetty,Undertow,Netty。

Tomcat

Spring Boot 默认使用 Tomcat 作为嵌入式 Web 容器。Tomcat 作为一个流行的 Web 容器,容易能够理解、配置和管理。可以通过使用spring-boot-starter-web来启用 Tomcat 容器。

Jetty

Jetty 同样是一个流行的嵌入式 Web 容器,它的缺省配置相对精简,从而有利快速启动。可以通过使用spring-boot-starter-jetty来启用 Jetty 容器。

Undertow

Undertow 是一个由 JBoss 开发的轻量级的嵌入式 Web 服务器。它具有出色的性能和低资源占用率,是一个适合微服务实现的 Web 服务器。可以使用spring-boot-starter-undertow来启用 Undertow 容器。

Netty

Netty是一个高性能的网络框架,需要引入spring-boot-starter-webflux和spring-boot-starter-reactor-netty来开启Netty作为Web容器。

使用

因为SpringBoot默认的是Tomcat作为Web容器,如果我们需要使用使用其他Web容器,那么需要排除Tomcat容器,再引入其他容器,Tomcat容器位于spring-boot-starter-web模块下,所以我们需要在maven的pom.xml中移除Tomcat,如下。

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

然后引入对应的Web容器,比如引入Undertow

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
XML 复制 全屏

然后可以在yml文件中配置相应容器的参数,如下配置undertow.

server:
  port: 8080
  undertow:
    threads:
      worker: 10
      io: 10
    direct-buffers: true

其他web容器可以根据实际情况配置,从 ServerProperties 配置文件中可以查看对应的Web容器的相关配置。