spring boot 2.0之Web Server

java

在spring boot 开发中,默认的web容器是tomcat,但是有时我们需要尝试下其他的web容器,这里主要是记录下容器切换的步骤。

1)、Tomcat -> jetty

tomcat 和 jetty 并存的情况下,因 tomcat 的加载优先级会高于 jetty,所以在依赖中需要排除 tomcat,这时候就可以在启动控制台看到是 Jetty 启动信息了。

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <!-- Exclude the Tomcat dependency --> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency> <!-- use Jetty instead --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jetty</artifactId> </dependency>
2019-11-10 00:11:49.319 INFO 11372 --- [ main] o.s.web.servlet.DispatcherServlet : Completed initialization in 6 ms 2019-11-10 00:11:49.354 INFO 11372 --- [ main] o.e.jetty.server.AbstractConnector : Started ServerConnector@25e49cb2{HTTP/1.1,[http/1.1]}{0.0.0.0:8080} 2019-11-10 00:11:49.358 INFO 11372 --- [ main] o.s.b.web.embedded.jetty.JettyWebServer : Jetty started on port(s) 8080 (http/1.1) with context path '/' 2019-11-10 00:11:49.361 INFO 11372 --- [ main] c.i.d.DiveInSpringBootApplication : Started DiveInSpringBootApplication in 1.846 seconds (JVM running for 2.733)

2)、使用 WebFlux 容器

spring-boot-starter-web 和 spring-boot-starter-webflux 并存的情况下,因 web 模块优先级高于 webflux,因此需要在 pom 文件去掉 web 模块,这时候就可以在启动控制台看到是 netty 启动信息了。

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency>
2019-11-10 00:42:34.179 INFO 13552 --- [ main] c.i.d.DiveInSpringBootApplication : No active profile set, falling back to default profiles: default 2019-11-10 00:42:35.909 INFO 13552 --- [ main] o.s.b.web.embedded.netty.NettyWebServer : Netty started on port(s): 8080 2019-11-10 00:42:35.918 INFO 13552 --- [ main] c.i.d.DiveInSpringBootApplication : Started DiveInSpringBootApplication in 2.134 seconds (JVM running for 3.992)

3)、Tomcat 自定义 Servlet Web Server

  • WebServerFactoryCustomizer

4)、Jetty 自定义 Reactive Web Server

  • ReactiveWebServerFactoryCustomizer

5)、启动方式

采用 SpringApplicationBuilder 启动方式可以自定义启动配置

@SpringBootApplication public class DiveInSpringBootApplication { public static void main(String[] args) { new SpringApplicationBuilder(DiveInSpringBootApplication.class) // 采用非 web 的方式启动 .web(WebApplicationType.NONE) .run(args); } }