内嵌容器原理与选择
Spring Boot 采用内嵌容器模式,将 Web 容器直接打包到应用中,简化部署流程。
内嵌容器原理
启动流程核心
Java
// SpringBoot 启动入口
public ConfigurableApplicationContext run(String... args) {
// 1. 创建 ApplicationContext
context = createApplicationContext();
// 2. 准备环境
prepareContext(context, environment, listeners, args);
// 3. 刷新上下文(启动容器)
refreshContext(context);
return context;
}
容器自动配置
Java
@AutoConfiguration
@ConditionalOnWebApplication(type = Type.SERVLET)
public class ServletWebServerFactoryAutoConfiguration {
@Bean
@ConditionalOnClass(Tomcat.class)
public ServletWebServerFactory tomcatServletWebServerFactory() {
return new TomcatServletWebServerFactory();
}
}
容器架构对比
| 特性 | Tomcat | Jetty | Undertow |
|---|---|---|---|
| 线程模型 | 阻塞 BIO/NIO | 非阻塞 | 非阻塞 NIO |
| 内存占用 | 中等 | 较低 | 较低 |
| 启动速度 | 中等 | 快 | 快 |
| 吞吐量 | 中等 | 中等 | 高 |
| 生态支持 | 最成熟 | 良好 | 良好 |
Tomcat 容器
默认容器特性
- Spring Boot 默认容器
- 成熟稳定,生态完善
- 支持 BIO 和 NIO 模式
切换 NIO 模式
YAML
server:
tomcat:
threads:
max: 200
min-spare: 10
accept-count: 100
max-connections: 10000
Jetty 容器
引入依赖
XML
<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-jetty</artifactId>
</dependency>
Jetty 配置
YAML
server:
jetty:
threads:
max: 200
min: 8
max-http-form-post-size: 200KB
Undertow 容器
引入依赖
XML
<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>
Undertow 配置
YAML
server:
undertow:
threads:
io: 16
worker: 200
buffer-size: 1024
direct-buffers: true
容器选型指南
Tomcat 适用场景
- 传统企业应用
- 需要成熟生态支持
- 团队熟悉 Tomcat 运维
Jetty 适用场景
- 低内存环境
- 长连接场景(WebSocket)
- 微服务轻量部署
Undertow 适用场景
- 高吞吐量需求
- 非阻塞 I/O 场景
- 对性能要求极高
注意:切换容器后需验证兼容性,部分框架组件可能依赖特定容器特性。
要点总结
- Tomcat 是默认容器,生态成熟,适合大多数场景
- Jetty 内存占用低,适合资源受限环境
- Undertow 吞吐量高,适合高并发场景
- 切换容器只需调整 Maven/Gradle 依赖
- 根据业务特点选择合适的容器
📝 发现内容有误?点击此处直接编辑