没有比较就没有伤害!Web 容器我们用的最多的还是 Tomcat,但是 Tomcat 的性能现在比起其他容器来说有点劣势!很多人可能更喜欢 Jetty 或者 netty,那么这么多 Web 容器,我们在使用 WebFlux 的时候该如何切换呢?一起来看本文的教程吧!

Spring WebFlux支持Netty,Undertow,Tomcat,Jetty和Servlet 3.1+容器。他们都适用于一个通用的Reactive Streams API。Spring WebFlux编程模型基于该通用API。

Spring WebFlux 默认是使用 Netty 作为 Web 容器的。如果要切换 Web 容器,只需要在 Maven 中做一下配置即可。


<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-netty</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </dependency> <!-- 添加 Undertow依赖 --> <!-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-undertow</artifactId> </dependency> --> <!-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jetty</artifactId> </dependency> -->

思路就是,先在 spring-boot-starter-webflux 容器中排除 netty 的 starter。然后添加需要的 Web 容器的 starter 即可。

 

那么怎么看自己是否配置成功呢?

有两种验证方法。第一种是在你的 idea 编辑器中的项目工程的 External Libraries 中查看你引入的 Web 容器的 starter 是否被加了进来。

第二种方法是,把你的工程跑起来,看看启动日志。以 Tomcat 为例,它在启动的日志可可以看到很多关于 tomcat 的日志信息。比如下面的内容:


Tomcat started on port(s): 8080 (http) with context path ''

Undertow是一个Java开发的灵活的高性能Web服务器,提供包括阻塞和基于NIO的非阻塞机制。Undertow是红帽公司的开源产品,是Wildfly默认的Web服务器。Undertow 用的人比较少,但是它性能不错。具体用法上面的配置中也有,其他的我就不在多说了。你都可以用起来,比较比较!