SpringBoot內置Tomcat的配置和切換 1.基本介紹 SpringBoot支持的webServer:Tomcat,Jetty,Undertow 因為在spring-boot-starter-web中,預設導入的是tomcat,因此啟動時使用的web容器就是tomcat。 同時 Spring ...
SpringBoot內置Tomcat的配置和切換
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)啟動項目,後臺輸出: