Spring Boot 内嵌容器Undertow

时间:2025-04-27 13:09:10

Spring Boot内嵌容器支持Tomcat、Jetty、Undertow。为什么选择Undertow?

这里有一篇文章,时间 2017年1月26日发布的:
Tomcat vs. Jetty vs. Undertow: Comparison of Spring Boot Embedded Servlet Containers
这篇文章详细测试了Spring Boot应用在三种容器下的性能和内存使用,内含完整的测试代码和测试流程。证明了Undertow在性能和内存使用上是最好的。

在Spring Boot中使用 Undertow 而不是 Tomcat

1、Maven示例:

<dependency>
    <groupId></groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId></groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId></groupId>
    <artifactId>spring-boot-starter-undertow</artifactId>
</dependency>

2、配置Undertow,示例:

= # Undertow access log directory.
=false # Enable access log.
=common # Format pattern for access logs.
=access_log. # Log file name prefix.
=true # Enable access log rotation.
=log # Log file name suffix.
-size= # Size of each buffer in bytes.
-per-region= # Number of buffer per region.
-buffers= # Allocate buffers outside the Java heap.
-threads= # Number of I/O threads to create for the worker.
-http-post-size=0 # Maximum size in bytes of the HTTP post content.
-threads= # Number of worker threads.

3、使用 Undertow 监听多个端口示例:

@Bean
public UndertowEmbeddedServletContainerFactory embeddedServletContainerFactory() {
    UndertowEmbeddedServletContainerFactory factory = new UndertowEmbeddedServletContainerFactory();
    (new UndertowBuilderCustomizer() {

        @Override
        public void customize(Builder builder) {
            (8080, "0.0.0.0");
        }

    });
    return factory;
}