前言
默認情況下,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依賴,如下所示:
<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構建的話,可以使用以下方式達到同樣的效果:
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
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以編程的方式去配置這些參數
@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版本之后,我們應該使用 ConfigurableServletWebServerFactory 和 JettyServletWebServerFactory類去配置Jetty參數: 創建ConfigurableServletWebServerFactory Bean
@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; }
原文文鏈
分類:
Spring Boot

