1. Undertow 简介
Undertow 是一个采用 Java 开发的灵活的高性能 Web 服务器,提供包括阻塞和基于 NIO 的非堵塞机制。Undertow 是红帽公司的开源产品,是 Wildfly 默认的 Web 服务器。Undertow 提供一个基础的架构用来构建 Web 服务器,这是一个完全为嵌入式设计的项目,提供易用的构建器 API,完全向下兼容 Java EE Servlet 3.1 和低级非堵塞的处理器。
2. Undertow特点
- 高性能 在多款同类产品的压测中,在高并发情况下表现出色。
- Servlet4.0 支持 它提供了对 Servlet4.0 的支持。
- Web Socket 完全支持,包括JSR-356,用以满足 Web 应用巨大数量的客户端。
- 内嵌式 它不需要容器,只需通过 API 即可快速搭建 Web 服务器。
- 灵活性 交由链式Handler配置和处理请求,可以最小化按需加载模块,无须加载多余功能。
- 轻量级 它是一个 内嵌Web 服务器, 由两个核心 Jar 包组成
3. 替换默认的Tomcat
Spring boot 默认使用 Tomcat 内嵌容器 。依赖于 spring-boot-starter-web 。我们只需要排除 Tomcat 依赖。引用Undertow 就可以了,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>
4. 自定义配置Undertow
其实到第三步已经可以愉快地玩耍了。你可以立即在 https://felord.cn 找到更多教程来学习Spring Boot。当然你也可以再折腾一番,通过在Spring Boot 配置文件application.yml中配置 ServerProperties 和ServerProperties.Undertow 的相关属性。 总结了一下比较陌生的ServerProperties.Undertow 的属性:
server:
undertow:
io-threads: 16
worker-threads: 256
buffer-size: 1024
buffers-per-region: 1024
direct-buffers: true
5. 总结
今天我们演示了如何用性能优良的 Undertow 来作为Spring Boot 的 Servlet Web 容器。其实在并发量不大的情况下 Undertow、和其它两款 Servlet Web 容器 Jetty 、Tomcat 的差距并不是很大。 Undertow 的优势是高并发下的吞吐量。你可以根据自己的实际需要来选择。
关注公众号:Felordcn获取更多资讯
个人博客:https://felord.cn