Spring Boot – 配置 Jetty 服务器

Spring Boot – 配置 Jetty 服务器

原文: https://howtodoinjava.com/spring-boot/configure-jetty-server/

默认情况下,Spring Boot 使用嵌入式 tomcat 服务器来运行应用程序。 有时,您可能需要使用 Jetty 服务器来代替 tomcat 服务器。 Spring Boot 将 Tomcat 和 Jetty 依赖项捆绑在一起,作为单独的启动器,以帮助简化此过程。 您可以通过以下简单步骤使用 Jetty。

添加spring-boot-starter-jetty依赖

您将需要更新pom.xml并添加对spring-boot-starter-jetty的依赖。 另外,您将需要排除默认添加的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 选项

要覆盖,默认 Jetty 运行时配置 – 您可以在application.properties文件中对其进行配置。

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 spanshot 版本有效。 在 Spring boot 2.0.0.RELEASE可用之后,您将使用ConfigurableServletWebServerFactoryJettyServletWebServerFactory类。

Create bean of type ConfigurableServletWebServerFactory

@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 应用程序中使用 jetty 代替 tomcat 服务器的问题。

学习愉快!

参考:配置 Jetty