Spring Boot – Jetty配置

阅读目录#

前言#

默认情况下,Spring Boot 会使用内置的 tomcat 容器去运行应用程序,但偶尔我们也会考虑使用 Jetty 去替代 Tomcat;
对于 Tomcat 和 Jetty,Spring Boot 分别提供了对应的 starter,以便尽可能的简化我们的开发过程;
当我们想使用 Jetty 的时候,可以参考以下步骤来使用。

添加 spring-boot-starter-jetty 依赖#

我们需要更新pom.xml文件,添加spring-boot-starter-jetty依赖,同时我们需要排除spring-boot-starter-web默认的spring-boot-starter-tomcat依赖,如下所示:

Copy
<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-jetty</artifactId> </dependency>

如果我们的工程是使用 Gradle 构建的话,可以使用以下方式达到同样的效果:

Copy
configurations { compile.exclude module: "spring-boot-starter-tomcat" }

dependencies {
compile("org.springframework.boot:spring-boot-starter-web:2.0.0.BUILD-SNAPSHOT")
compile("org.springframework.boot:spring-boot-starter-jetty:2.0.0.BUILD-SNAPSHOT")
}

配置 Jetty 参数#

我们可以在 application.properties 配置文件里配置相关参数,去覆盖 Jetty 默认使用的运行参数:
application.properties

Copy
server.port=8080 server.servlet.context-path=/home

####Jetty specific properties########

server.jetty.acceptors= # Number of acceptor threads to use.
server.jetty.max-http-post-size=0 # Maximum size in bytes of the HTTP post or put content.
server.jetty.selectors= # Number of selector threads to use.

同样,我们可以通过JettyEmbeddedServletContainerFactory bean 以编程的方式去配置这些参数

Copy
@Bean public JettyEmbeddedServletContainerFactory jettyEmbeddedServletContainerFactory() { JettyEmbeddedServletContainerFactory jettyContainer = new JettyEmbeddedServletContainerFactory(); jettyContainer.setPort(9000); jettyContainer.setContextPath("/home"); return jettyContainer; }

Spring boot 2.0.0.RELEASE 版本之后的更新#

以上代码针对的是 Spring Boot Snapshot 版本,在 Spring boot 2.0.0.RELEASE 版本之后,我们应该使用 ConfigurableServletWebServerFactoryJettyServletWebServerFactory类去配置 Jetty 参数:
创建ConfigurableServletWebServerFactory Bean

Copy
@Bean public ConfigurableServletWebServerFactory webServerFactory() { JettyServletWebServerFactory factory = new JettyServletWebServerFactory(); factory.setPort(9000); factory.setContextPath("/myapp"); factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notfound.html")); return factory; }

原文文链#

Site4J