SpringBoot工程替换web容器tomcat为undertow

1,481 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第31天,点击查看活动详情

SpringBoot工程替换web容器tomcat为undertow

Springboot的默认的web容器是tomcat,同时SpringBoot也支持jetty和undertow;一般情况下,使用tomcat足够了,但是有时候因为性能问题,需要替换为其他容器,如:undertow

Undertow是个啥?

Undertow 是一个采用 Java 开发的灵活的高性能 Web 服务器,提供包括阻塞和基于 NIO 的非堵塞机制。Undertow 是红帽公司的开源产品;

Undertow 提供一个基础的架构用来构建 Web 服务器,这是一个完全为嵌入式设计的项目,提供易用的构建器 API,完全兼容 Java EE Servlet 4 和低级非堵塞的处理器。

Undertow 设计为完全可嵌入的,并具有易于使用的流畅的 Builder API。 Undertow 的生命周期完全由嵌入应用程序控制。

需要替换tomcat为undertow吗?

是否需要主要看系统应用的使用情况而定;

因为通过大佬测试发现,在高并发系统中,Tomcat相对来说比较弱。在相同的机器配置下,模拟相等的请求数,Undertow在性能和内存使用方面都是最优的。并且Undertow新版本默认使用持久连接,这将会进一步提高它的并发吞吐能力。

所以,如果是高并发的业务系统,Undertow是最佳选择;

替换方法

因为SpringBoot的内置容器是tomcat,所以要替换tomcat,必须是先排除,后添加;

具体替换方法如下:

1、如果是gradle工程,有两种方式;

方式一、在全局配置中修改; 在build.gradle文中 添加exclude

exclude module:'spring-boot-starter-tomcat'

在这里插入图片描述

方式二、在compile排除:

 compile("org.springframework.boot:spring-boot-starter-web:${springBootVersion}") {
            exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat'
  }

最后添加undertow依赖:


	compile 'org.springframework.boot:spring-boot-starter-undertow:2.7.0'

2、如果是maven工程:

直接排除后添加依赖既可;

<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>

3、如果只是替换tomcat版本:

先排除内置版本,然后添加指定tomcat版本

  compile("org.springframework.boot:spring-boot-starter-web:${springBootVersion}") {
            exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat'
  }
  compile 'org.apache.tomcat.embed:tomcat-embed-core:8.5.51'
  compile 'org.apache.tomcat.embed:tomcat-embed-el:8.5.51'
  compile 'org.apache.tomcat.embed:tomcat-embed-websocket:8.5.51'

maven项目只需要修改pom.xml文件 添加tomcat指定版本

 <tomcat.version>9.0.58</tomcat.version>