全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-18 8 分钟 ✍️ juanwangdev

内嵌容器原理与选择

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();
    }
}

容器架构对比

特性TomcatJettyUndertow
线程模型阻塞 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 依赖
  • 根据业务特点选择合适的容器

📝 发现内容有误?点击此处直接编辑

← 上一篇 Undertow性能调优
下一篇 → 内嵌容器监控与诊断
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库