1.基本介绍
-
SpringBoot支持的webServer:Tomcat,Jetty,Undertow
-
因为在spring-boot-starter-web中,默认导入的是tomcat,因此启动时使用的web容器就是tomcat。
-
同时 SpringBoot 也支持对Tomcat(或者Jetty、Undertow)的配置和切换。
2.内置Tomcat的配置
2.1通过application.yml完成配置
内置Tomcat的配置和ServerProperties.java关联,可以通过查看源码得知有哪些属性配置。
例如:
server: | |
port: 9090 #端口,默认8080 | |
tomcat: | |
threads: | |
max: 100 # web容器最大工作线程数,默认200 | |
min-spare: 5 # 最小工作线程数,默认10 | |
accept-count: 200 # tomcat启动的线程达到最大值后,接受排队的请求个数,默认100 | |
max-connections: 2000 #最大连接数(并发数),默认8192 | |
connection-timeout: 10000 #建立连接的超时时间,单位为ms |
2.2通过类来配置tomcat
配置文件可以配置得更全面,通过类来配置灵活性没有那么好
package com.li.thymeleaf.config; | |
import org.springframework.boot.web.server.WebServerFactoryCustomizer; | |
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory; | |
import org.springframework.stereotype.Component; | |
/** | |
* @author 李 | |
* @version 1.0 | |
* 通过类来配置Tomcat | |
*/ | |
@Component | |
public class TomcatInItConfig implements | |
WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> { | |
@Override | |
public void customize(ConfigurableServletWebServerFactory server) { | |
server.setPort(9090); | |
//还可以进行其他设置... | |
} | |
} |
3.切换WebServer
演示如何将默认配置的webServer切换为Undertow。
(1)修改pom.xml,因为默认引入了spring-boot-starter-tomcat,因此要排除tomcat,再加入Undertow依赖
<!--导入SpringBoot父工程--> | |
<parent> | |
<artifactId>spring-boot-starter-parent</artifactId> | |
<groupId>org.springframework.boot</groupId> | |
<version>2.5.3</version> | |
</parent> | |
<dependencies> | |
<!--导入web场景启动器--> | |
<dependency> | |
<groupId>org.springframework.boot</groupId> | |
<artifactId>spring-boot-starter-web</artifactId> | |
<!--排除tomcat starter--> | |
<exclusions> | |
<exclusion> | |
<groupId>org.springframework.boot</groupId> | |
<artifactId>spring-boot-starter-tomcat</artifactId> | |
</exclusion> | |
</exclusions> | |
</dependency> | |
<!--引入undertow--> | |
<dependency> | |
<groupId>org.springframework.boot</groupId> | |
<artifactId>spring-boot-starter-undertow</artifactId> | |
</dependency> | |
</dependencies> |
(2)启动项目,后台输出: