嵌入式Web服务器

每个Spring Boot web应用都包含一个嵌入式web服务器。此特性引出了许多操作问题,包括如何更换嵌入式服务器以及如何配置嵌入式服务器。本节将回答这些问题。

使用其他Web服务器

许多Spring Boot starter都包含默认的嵌入式容器。

  • 对于Servlet栈应用,spring-boot-starter-web 通过包含 spring-boot-starter-tomcat 默认集成了Tomcat,但你可以使用 spring-boot-starter-jettyspring-boot-starter-undertow 代替。

  • 对于响应式栈应用,spring-boot-starter-webflux 通过包含 spring-boot-starter-reactor-netty 默认集成了Reactor Netty,但你可以使用 spring-boot-starter-tomcatspring-boot-starter-jettyspring-boot-starter-undertow 代替。

切换到不同的HTTP服务器时,你需要将默认依赖项替换为你所需的依赖项。为帮助完成此过程,Spring Boot为每个支持的HTTP服务器提供了单独的starter。

以下Maven示例展示了如何为Spring MVC排除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>

以下Gradle示例配置了必要的依赖项和模块替换(module replacement),以便在Spring WebFlux中用Undertow替换Reactor Netty

dependencies {
	implementation "org.springframework.boot:spring-boot-starter-undertow"
	implementation "org.springframework.boot:spring-boot-starter-webflux"
	modules {
		module("org.springframework.boot:spring-boot-starter-reactor-netty") {
			replacedBy("org.springframework.boot:spring-boot-starter-undertow", "Use Undertow instead of Reactor Netty")
		}
	}
}
使用WebClient类需要spring-boot-starter-reactor-netty,因此即使你需要包含不同的HTTP服务器,也可能需要保留对Netty的依赖。

禁用Web服务器

如果你的类路径包含启动Web服务器所需的组件,Spring Boot将自动启动它。要禁用此行为,请在application.properties中配置WebApplicationType,如以下示例所示

  • 属性文件 (Properties)

  • YAML文件 (YAML)

spring.main.web-application-type=none
spring:
  main:
    web-application-type: "none"

更改HTTP端口

在独立应用中,主HTTP端口默认为8080,但可以通过server.port进行设置(例如,在application.properties中或作为系统属性)。由于对Environment值的宽松绑定,你也可以使用SERVER_PORT(例如,作为操作系统环境变量)。

要完全关闭HTTP端点但仍创建WebApplicationContext,请使用server.port=-1(这样做有时对测试有用)。

更多详细信息,请参阅“Spring Boot特性”部分中的自定义嵌入式Servlet容器,或查看ServerProperties类。

使用随机未分配的HTTP端口

要扫描可用端口(使用操作系统原生方法防止冲突),请使用server.port=0

在运行时发现HTTP端口

你可以从日志输出或通过WebServerApplicationContext及其WebServer访问服务器运行的端口。获取端口并确保它已初始化的最佳方法是添加一个类型为ApplicationListener<WebServerInitializedEvent>@Bean,并在事件发布时从事件中提取容器。

使用@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)的测试还可以通过使用@LocalServerPort注解将实际端口注入字段,如以下示例所示

  • Java

  • Kotlin

import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.server.LocalServerPort;

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class MyWebIntegrationTests {

	@LocalServerPort
	int port;

	// ...

}
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment
import org.springframework.boot.test.web.server.LocalServerPort

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class MyWebIntegrationTests {

	@LocalServerPort
	var port = 0

	// ...

}

@LocalServerPort@Value("${local.server.port}")的元注解。不要尝试在常规应用中注入端口。正如我们刚刚看到的,该值仅在容器初始化后设置。与测试相反,应用代码回调处理较早(在值实际可用之前)。

启用HTTP响应压缩

Jetty、Tomcat、Reactor Netty和Undertow都支持HTTP响应压缩。可以在application.properties中启用,如下所示

  • 属性文件 (Properties)

  • YAML文件 (YAML)

server.compression.enabled=true
server:
  compression:
    enabled: true

默认情况下,响应长度必须至少为2048字节才会执行压缩。你可以通过设置server.compression.min-response-size属性来配置此行为。

默认情况下,仅当响应内容类型为以下之一时才进行压缩

  • text/html

  • text/xml

  • text/plain

  • text/css

  • text/javascript

  • application/javascript

  • application/json

  • application/xml

你可以通过设置server.compression.mime-types属性来配置此行为。

配置SSL

可以通过声明性地设置各种server.ssl.*属性来配置SSL,通常在application.propertiesapplication.yaml中。有关所有支持属性的详细信息,请参阅Ssl

以下示例显示了使用Java KeyStore文件设置SSL属性

  • 属性文件 (Properties)

  • YAML文件 (YAML)

server.port=8443
server.ssl.key-store=classpath:keystore.jks
server.ssl.key-store-password=secret
server.ssl.key-password=another-secret
server:
  port: 8443
  ssl:
    key-store: "classpath:keystore.jks"
    key-store-password: "secret"
    key-password: "another-secret"

使用如上所示的配置意味着应用不再支持端口8080上的纯HTTP连接器。Spring Boot不支持通过application.properties同时配置HTTP连接器和HTTPS连接器。如果你想同时拥有两者,你需要以编程方式配置其中一个。我们建议使用application.properties配置HTTPS,因为HTTP连接器是两者中更容易以编程方式配置的。

使用PEM编码文件

你可以使用PEM编码的文件代替Java KeyStore文件。应尽可能使用PKCS#8密钥文件。PEM编码的PKCS#8密钥文件以-----BEGIN PRIVATE KEY----------BEGIN ENCRYPTED PRIVATE KEY-----头开始。

如果你的文件是其他格式,例如PKCS#1 (-----BEGIN RSA PRIVATE KEY-----) 或 SEC 1 (-----BEGIN EC PRIVATE KEY-----),可以使用OpenSSL将其转换为PKCS#8

openssl pkcs8 -topk8 -nocrypt -in <input file> -out <output file>

以下示例显示了使用PEM编码的证书和私钥文件设置SSL属性

  • 属性文件 (Properties)

  • YAML文件 (YAML)

server.port=8443
server.ssl.certificate=classpath:my-cert.crt
server.ssl.certificate-private-key=classpath:my-cert.key
server.ssl.trust-certificate=classpath:ca-cert.crt
server:
  port: 8443
  ssl:
    certificate: "classpath:my-cert.crt"
    certificate-private-key: "classpath:my-cert.key"
    trust-certificate: "classpath:ca-cert.crt"

使用SSL Bundle

或者,可以在SSL bundle中配置SSL信任材料,并将其应用于web服务器,如下例所示

  • 属性文件 (Properties)

  • YAML文件 (YAML)

server.port=8443
server.ssl.bundle=example
server:
  port: 8443
  ssl:
    bundle: "example"

server.ssl.bundle属性不能与server.ssl下的独立Java KeyStore或PEM属性选项结合使用。

使用bundle时,server.ssl.ciphersserver.ssl.enabled-protocolsserver.ssl.protocol属性也会被忽略。这些属性应改为使用spring.ssl.bundle.<type>.<name>.options属性定义。

配置服务器名称指示 (SNI)

可以配置Tomcat、Netty和Undertow为不同的主机名使用独特的SSL信任材料以支持服务器名称指示(SNI)。Jetty不支持SNI配置,但如果提供多个证书,Jetty可以自动设置SNI

假设已配置了名为webweb-alt1web-alt2SSL bundle,可以使用以下配置将每个bundle分配给嵌入式web服务器提供服务的主机名

  • 属性文件 (Properties)

  • YAML文件 (YAML)

server.port=8443
server.ssl.bundle=web
server.ssl.server-name-bundles[0].server-name=alt1.example.com
server.ssl.server-name-bundles[0].bundle=web-alt1
server.ssl.server-name-bundles[1].server-name=alt2.example.com
server.ssl.server-name-bundles[1].bundle=web-alt2
server:
  port: 8443
  ssl:
    bundle: "web"
    server-name-bundles:
      - server-name: "alt1.example.com"
        bundle: "web-alt1"
      - server-name: "alt2.example.com"
        bundle: "web-alt2"

server.ssl.bundle指定的bundle将用于默认主机以及任何不支持SNI的客户端。如果配置了任何server.ssl.server-name-bundles,则必须配置此默认bundle。

配置HTTP/2

你可以通过server.http2.enabled配置属性在Spring Boot应用中启用HTTP/2支持。支持h2(通过TLS的HTTP/2)和h2c(通过TCP的HTTP/2)。要使用h2,还必须启用SSL。如果未启用SSL,将使用h2c。例如,当你的应用在执行TLS终止的代理服务器后运行时,你可能希望使用h2c

使用Tomcat配置HTTP/2

Spring Boot默认集成了Tomcat 10.1.x,它开箱即用地支持h2ch2。另外,如果主机操作系统上安装了libtcnative及其依赖项,你可以使用它来支持h2

如果库目录尚未可用,则必须使其对JVM库路径可用。你可以通过JVM参数实现,例如-Djava.library.path=/usr/local/opt/tomcat-native/lib。更多内容请参阅Tomcat官方文档

使用Jetty配置HTTP/2

要支持HTTP/2,Jetty需要额外的org.eclipse.jetty.http2:jetty-http2-server依赖项。要使用h2c,不需要其他依赖项。要使用h2,你还需要根据你的部署选择以下依赖项之一

  • org.eclipse.jetty:jetty-alpn-java-server 以使用JDK内置支持

  • org.eclipse.jetty:jetty-alpn-conscrypt-serverConscrypt库

使用Reactor Netty配置HTTP/2

spring-boot-webflux-starter默认使用Reactor Netty作为服务器。Reactor Netty开箱即用地支持h2ch2。为了获得最佳运行时性能,此服务器还支持使用原生库的h2。要启用此功能,你的应用需要添加额外的依赖项。

Spring Boot管理io.netty:netty-tcnative-boringssl-static "uber jar" 的版本,该jar包含适用于所有平台的原生库。开发者可以选择使用分类器仅导入所需的依赖项(参见Netty官方文档)。

使用Undertow配置HTTP/2

Undertow开箱即用地支持h2ch2

配置Web服务器

通常,你应该首先考虑使用许多可用的配置键之一,并通过在application.propertiesapplication.yaml文件中添加新条目来定制Web服务器。请参阅发现外部属性的内置选项server.*命名空间非常有用,它包括server.tomcat.*server.jetty.*等命名空间,用于服务器特定特性。请参阅常用应用属性列表。

前面几节已经涵盖了许多常见用例,例如压缩、SSL或HTTP/2。然而,如果你的用例没有对应的配置键,你应该考虑使用WebServerFactoryCustomizer。你可以声明这样一个组件并访问与你选择的服务器相关的工厂:你应该选择所选服务器(Tomcat、Jetty、Reactor Netty、Undertow)和所选web栈(servlet或reactive)的变体。

以下示例是使用spring-boot-starter-web(servlet栈)的Tomcat

  • Java

  • Kotlin

import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.stereotype.Component;

@Component
public class MyTomcatWebServerCustomizer implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {

	@Override
	public void customize(TomcatServletWebServerFactory factory) {
		// customize the factory here
	}

}
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory
import org.springframework.boot.web.server.WebServerFactoryCustomizer
import org.springframework.stereotype.Component

@Component
class MyTomcatWebServerCustomizer : WebServerFactoryCustomizer<TomcatServletWebServerFactory?> {

	override fun customize(factory: TomcatServletWebServerFactory?) {
		// customize the factory here
	}

}
Spring Boot在内部使用该基础设施来自动配置服务器。自动配置的WebServerFactoryCustomizer bean的排序为0,将在任何用户定义的customizer之前处理,除非它有明确指定的排序。

一旦使用customizer获得了对WebServerFactory的访问权,你就可以使用它来配置特定部分,如连接器、服务器资源或服务器本身——所有这些都使用服务器特定的API。

此外,Spring Boot提供

服务器 Servlet栈 响应式栈

Tomcat

TomcatServletWebServerFactory

TomcatReactiveWebServerFactory

Jetty

JettyServletWebServerFactory

JettyReactiveWebServerFactory

Undertow

UndertowServletWebServerFactory

UndertowReactiveWebServerFactory

Reactor

不适用 (N/A)

NettyReactiveWebServerFactory

作为最后的手段,你也可以声明自己的WebServerFactory bean,这将覆盖Spring Boot提供的bean。这样做时,自动配置的customizer仍然会应用到你的自定义工厂上,因此请谨慎使用此选项。

向应用添加Servlet、Filter或Listener

在servlet栈应用中,即使用spring-boot-starter-web时,有两种方法可以将ServletFilterServletContextListener以及Servlet API支持的其他listener添加到应用中

使用Spring Bean添加Servlet、Filter或Listener

要使用Spring bean添加ServletFilter或servlet *Listener,必须为其提供@Bean定义。这在你想要注入配置或依赖项时非常有用。但是,你必须非常小心,不要导致太多其他bean的提前初始化,因为它们必须在应用生命周期的早期安装到容器中。(例如,让它们依赖于你的DataSource或JPA配置不是一个好主意。)你可以通过在首次使用时而不是在初始化时懒惰地初始化bean来规避此类限制。

对于filter和servlet,你还可以通过添加FilterRegistrationBeanServletRegistrationBean来添加映射和初始化参数,而不是或除了底层组件之外。

如果在filter注册中未指定dispatcherType,则使用REQUEST。这与servlet规范的默认dispatcher类型一致。

与任何其他Spring bean一样,你可以定义servlet filter bean的顺序;请务必查看将Servlet、Filter和Listener注册为Spring Bean部分。

禁用Servlet或Filter的注册

前所述,任何ServletFilter bean都会自动注册到servlet容器中。要禁用特定FilterServlet bean的注册,请为其创建一个注册bean并将其标记为禁用,如以下示例所示

  • Java

  • Kotlin

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration(proxyBeanMethods = false)
public class MyFilterConfiguration {

	@Bean
	public FilterRegistrationBean<MyFilter> registration(MyFilter filter) {
		FilterRegistrationBean<MyFilter> registration = new FilterRegistrationBean<>(filter);
		registration.setEnabled(false);
		return registration;
	}

}
import org.springframework.boot.web.servlet.FilterRegistrationBean
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration

@Configuration(proxyBeanMethods = false)
class MyFilterConfiguration {

	@Bean
	fun registration(filter: MyFilter): FilterRegistrationBean<MyFilter> {
		val registration = FilterRegistrationBean(filter)
		registration.isEnabled = false
		return registration
	}

}

使用类路径扫描添加Servlet、Filter和Listener

通过@ServletComponentScan注解@Configuration类并指定包含要注册组件的包,可以自动将使用@WebServlet@WebFilter@WebListener注解的类注册到嵌入式servlet容器。默认情况下,@ServletComponentScan从被注解类的包开始扫描。

配置访问日志

可以通过各自的命名空间为Tomcat、Undertow和Jetty配置访问日志。

例如,以下设置使用自定义模式在Tomcat上记录访问。

  • 属性文件 (Properties)

  • YAML文件 (YAML)

server.tomcat.basedir=my-tomcat
server.tomcat.accesslog.enabled=true
server.tomcat.accesslog.pattern=%t %a %r %s (%D microseconds)
server:
  tomcat:
    basedir: "my-tomcat"
    accesslog:
      enabled: true
      pattern: "%t %a %r %s (%D microseconds)"
日志的默认位置是相对于Tomcat基础目录的logs目录。默认情况下,logs目录是一个临时目录,因此你可能希望固定Tomcat的基础目录或为日志使用绝对路径。在上述示例中,日志位于应用程序工作目录相对于my-tomcat/logs的位置。

Undertow的访问日志也可以以类似的方式配置,如以下示例所示

  • 属性文件 (Properties)

  • YAML文件 (YAML)

server.undertow.accesslog.enabled=true
server.undertow.accesslog.pattern=%t %a %r %s (%D milliseconds)
server.undertow.options.server.record-request-start-time=true
server:
  undertow:
    accesslog:
      enabled: true
      pattern: "%t %a %r %s (%D milliseconds)"
    options:
      server:
        record-request-start-time: true

请注意,除了启用访问日志和配置其模式外,还启用了记录请求开始时间。在访问日志模式中包含响应时间(%D)时,这是必需的。日志存储在应用程序工作目录相对于logs目录的位置。你可以通过设置server.undertow.accesslog.dir属性来自定义此位置。

最后,Jetty的访问日志也可以如下配置

  • 属性文件 (Properties)

  • YAML文件 (YAML)

server.jetty.accesslog.enabled=true
server.jetty.accesslog.filename=/var/log/jetty-access.log
server:
  jetty:
    accesslog:
      enabled: true
      filename: "/var/log/jetty-access.log"

默认情况下,日志会重定向到System.err。更多详细信息,请参阅Jetty文档。

在前端代理服务器后运行

如果你的应用运行在代理、负载均衡器后面或云中,请求信息(如主机、端口、方案等)可能会在传输过程中发生变化。你的应用可能运行在10.10.10.10:8080上,但HTTP客户端应该只能看到example.org

RFC7239 "Forwarded Headers"定义了Forwarded HTTP头;代理可以使用此头提供关于原始请求的信息。你可以配置你的应用读取这些头并在创建链接并将其发送给客户端(在HTTP 302响应、JSON文档或HTML页面中)时自动使用这些信息。还有非标准头,如X-Forwarded-HostX-Forwarded-PortX-Forwarded-ProtoX-Forwarded-SslX-Forwarded-Prefix

如果代理添加了常用的X-Forwarded-ForX-Forwarded-Proto头,将server.forward-headers-strategy设置为NATIVE就足以支持这些。使用此选项,Web服务器本身原生支持此特性;你可以查看其具体文档了解特定行为。

如果这还不够,Spring Framework为servlet栈提供了ForwardedHeaderFilter,为响应式栈提供了ForwardedHeaderTransformer。你可以通过将server.forward-headers-strategy设置为FRAMEWORK在你的应用中使用它们。

如果你使用Tomcat并在代理端终止SSL,则应将server.tomcat.redirect-context-root设置为false。这允许在执行任何重定向之前尊重X-Forwarded-Proto头。
如果你的应用在受支持的云平台上运行server.forward-headers-strategy属性默认为NATIVE。在所有其他情况下,它默认为NONE

自定义Tomcat的代理配置

如果你使用Tomcat,还可以配置用于承载“转发”信息的头名称,如以下示例所示

  • 属性文件 (Properties)

  • YAML文件 (YAML)

server.tomcat.remoteip.remote-ip-header=x-your-remote-ip-header
server.tomcat.remoteip.protocol-header=x-your-protocol-header
server:
  tomcat:
    remoteip:
      remote-ip-header: "x-your-remote-ip-header"
      protocol-header: "x-your-protocol-header"

Tomcat还配置了一个正则表达式,用于匹配应受信任的内部代理。请参阅附录中server.tomcat.remoteip.internal-proxies条目了解其默认值。你可以通过在application.properties中添加条目来自定义valva的配置,如以下示例所示

  • 属性文件 (Properties)

  • YAML文件 (YAML)

server.tomcat.remoteip.internal-proxies=192\.168\.\d{1,3}\.\d{1,3}
server:
  tomcat:
    remoteip:
      internal-proxies: "192\\.168\\.\\d{1,3}\\.\\d{1,3}"
您可以通过将 internal-proxies 设置为空来信任所有代理(但请勿在生产环境这样做)。

您可以通过关闭自动配置(为此,将 server.forward-headers-strategy 设置为 NONE)并使用 WebServerFactoryCustomizer bean 添加一个新的阀门实例,来完全控制 Tomcat 的 RemoteIpValve 的配置。

使用 Tomcat 启用多个连接器

您可以将一个 Connector 添加到 TomcatServletWebServerFactory 中,这允许使用多个连接器,包括 HTTP 和 HTTPS 连接器,如以下示例所示

  • Java

  • Kotlin

import org.apache.catalina.connector.Connector;

import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration(proxyBeanMethods = false)
public class MyTomcatConfiguration {

	@Bean
	public WebServerFactoryCustomizer<TomcatServletWebServerFactory> connectorCustomizer() {
		return (tomcat) -> tomcat.addAdditionalTomcatConnectors(createConnector());
	}

	private Connector createConnector() {
		Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
		connector.setPort(8081);
		return connector;
	}

}
import org.apache.catalina.connector.Connector
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory
import org.springframework.boot.web.server.WebServerFactoryCustomizer
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration

@Configuration(proxyBeanMethods = false)
class MyTomcatConfiguration {

	@Bean
	fun connectorCustomizer(): WebServerFactoryCustomizer<TomcatServletWebServerFactory> {
		return WebServerFactoryCustomizer { tomcat: TomcatServletWebServerFactory ->
			tomcat.addAdditionalTomcatConnectors(
				createConnector()
			)
		}
	}

	private fun createConnector(): Connector {
		val connector = Connector("org.apache.coyote.http11.Http11NioProtocol")
		connector.port = 8081
		return connector
	}

}

启用 Tomcat 的 MBean 注册表

嵌入式 Tomcat 的 MBean 注册表默认是禁用的。这可以最大程度地减少 Tomcat 的内存占用。如果您想使用 Tomcat 的 MBean,例如以便 Micrometer 可以使用它们来暴露指标,您必须使用 server.tomcat.mbeanregistry.enabled 属性来启用它,如以下示例所示

  • 属性文件 (Properties)

  • YAML文件 (YAML)

server.tomcat.mbeanregistry.enabled=true
server:
  tomcat:
    mbeanregistry:
      enabled: true

使用 Undertow 启用多个监听器

UndertowBuilderCustomizer 添加到 UndertowServletWebServerFactory 中,并将一个监听器添加到 io.undertow.Undertow.Builder 中,如以下示例所示

  • Java

  • Kotlin

import io.undertow.Undertow.Builder;

import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration(proxyBeanMethods = false)
public class MyUndertowConfiguration {

	@Bean
	public WebServerFactoryCustomizer<UndertowServletWebServerFactory> undertowListenerCustomizer() {
		return (factory) -> factory.addBuilderCustomizers(this::addHttpListener);
	}

	private Builder addHttpListener(Builder builder) {
		return builder.addHttpListener(8080, "0.0.0.0");
	}

}
import io.undertow.Undertow
import org.springframework.boot.web.embedded.undertow.UndertowBuilderCustomizer
import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory
import org.springframework.boot.web.server.WebServerFactoryCustomizer
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration

@Configuration(proxyBeanMethods = false)
class MyUndertowConfiguration {

	@Bean
	fun undertowListenerCustomizer(): WebServerFactoryCustomizer<UndertowServletWebServerFactory> {
		return WebServerFactoryCustomizer { factory: UndertowServletWebServerFactory ->
			factory.addBuilderCustomizers(
				UndertowBuilderCustomizer { builder: Undertow.Builder -> addHttpListener(builder) })
		}
	}

	private fun addHttpListener(builder: Undertow.Builder): Undertow.Builder {
		return builder.addHttpListener(8080, "0.0.0.0")
	}

}

使用 @ServerEndpoint 创建 WebSocket 端点

如果您想在使用了嵌入式容器的 Spring Boot 应用程序中使用 @ServerEndpoint,您必须声明一个单独的 ServerEndpointExporter @Bean,如以下示例所示

  • Java

  • Kotlin

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration(proxyBeanMethods = false)
public class MyWebSocketConfiguration {

	@Bean
	public ServerEndpointExporter serverEndpointExporter() {
		return new ServerEndpointExporter();
	}

}
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.web.socket.server.standard.ServerEndpointExporter

@Configuration(proxyBeanMethods = false)
class MyWebSocketConfiguration {

	@Bean
	fun serverEndpointExporter(): ServerEndpointExporter {
		return ServerEndpointExporter()
	}

}

前面示例中所示的 bean 会将所有带有 @ServerEndpoint 注解的 bean 注册到底层 WebSocket 容器。部署到独立的 servlet 容器时,此角色由 servlet 容器初始化器执行,并且不需要 ServerEndpointExporter bean。