WebSocket 支持

从版本 4.1 开始,Spring Integration 支持 WebSocket。它基于 Spring Framework 的 web-socket 模块的架构、基础设施和 API。因此,许多 Spring WebSocket 的组件(例如 SubProtocolHandlerWebSocketClient)和配置选项(例如 @EnableWebSocketMessageBroker)可以在 Spring Integration 中重用。更多信息请参阅 Spring Framework WebSocket 支持 一章在 Spring Framework 参考手册中。

您需要在项目中包含此依赖项

  • Maven

  • Gradle

<dependency>
    <groupId>org.springframework.integration</groupId>
    <artifactId>spring-integration-websocket</artifactId>
    <version>6.4.4</version>
</dependency>
compile "org.springframework.integration:spring-integration-websocket:6.4.4"

对于服务器端,必须显式包含 org.springframework:spring-webmvc 依赖项。

Spring Framework 的 WebSocket 基础设施基于 Spring 消息基础构建,并提供了一个基本的消息框架,该框架基于 Spring Integration 使用的相同的 MessageChannel 实现和 MessageHandler 实现(以及一些 POJO 方法的注解映射)。因此,Spring Integration 可以直接参与 WebSocket 流,即使没有 WebSocket 适配器。为此,您可以使用适当的注解配置 Spring Integration @MessagingGateway,如下例所示

@MessagingGateway
@Controller
public interface WebSocketGateway {

    @MessageMapping("/greeting")
    @SendToUser("/queue/answer")
    @Gateway(requestChannel = "greetingChannel")
    String greeting(String payload);

}

概览

由于 WebSocket 协议本质上是流式的,并且我们可以同时向 WebSocket 发送和接收消息,因此无论是在客户端还是服务器端,我们都可以处理适当的 WebSocketSession。为了封装连接管理和 WebSocketSession 注册,提供了 IntegrationWebSocketContainer,其包含 ClientWebSocketContainerServerWebSocketContainer 实现。得益于 WebSocket API 及其在 Spring Framework 中的实现(包含许多扩展),服务器端和客户端(当然,从 Java 的角度来看)都使用相同的类。因此,大多数连接和 WebSocketSession 注册选项在两端是相同的。这使我们可以重用许多配置项和基础设施钩子来构建服务器端和客户端的 WebSocket 应用程序。以下示例展示了组件如何同时服务于这两个目的

//Client side
@Bean
public WebSocketClient webSocketClient() {
    return new SockJsClient(Collections.singletonList(new WebSocketTransport(new JettyWebSocketClient())));
}

@Bean
public IntegrationWebSocketContainer clientWebSocketContainer() {
    return new ClientWebSocketContainer(webSocketClient(), "ws://my.server.com/endpoint");
}

//Server side
@Bean
public IntegrationWebSocketContainer serverWebSocketContainer() {
    return new ServerWebSocketContainer("/endpoint").withSockJs();
}

IntegrationWebSocketContainer 旨在实现双向消息传递,可以在入站和出站通道适配器之间共享(见下文);在使用单向(发送或接收)WebSocket 消息传递时,也可以仅被其中一个引用。它可以在不使用任何通道适配器的情况下使用,但在此情况下,IntegrationWebSocketContainer 仅充当 WebSocketSession 注册表的作用。

ServerWebSocketContainer 实现了 WebSocketConfigurer 以便将内部的 IntegrationWebSocketContainer.IntegrationWebSocketHandler 注册为 Endpoint。它在目标供应商 WebSocket Container 的 ServletWebSocketHandlerRegistry 中,根据提供的 paths 和其他服务器 WebSocket 选项(如 HandshakeHandlerSockJS fallback)进行注册。此注册是通过基础设施组件 WebSocketIntegrationConfigurationInitializer 完成的,它执行与 @EnableWebSocket 注解相同的功能。这意味着,通过使用 @EnableIntegration(或应用程序上下文中的任何 Spring Integration 命名空间),您可以省略 @EnableWebSocket 声明,因为 Spring Integration 基础设施会检测所有 WebSocket 端点。

从版本 6.1 开始,可以使用提供的 URI 配置 ClientWebSocketContainer,而不是使用 uriTemplateuriVariables 的组合。当 URI 的某些部分需要自定义编码时,这非常有用。请参阅 UriComponentsBuilder API 以获取便利。

WebSocket 入站通道适配器

WebSocketInboundChannelAdapter 实现了 WebSocketSession 交互的接收部分。您必须为其提供一个 IntegrationWebSocketContainer,适配器会将自身注册为 WebSocketListener,以处理传入消息和 WebSocketSession 事件。

IntegrationWebSocketContainer 中只能注册一个 WebSocketListener

对于 WebSocket 子协议,WebSocketInboundChannelAdapter 可以配置 SubProtocolHandlerRegistry 作为第二个构造函数参数。适配器将委托给 SubProtocolHandlerRegistry,以确定接受的 WebSocketSession 适用的 SubProtocolHandler,并根据子协议实现将 WebSocketMessage 转换为 Message

默认情况下,WebSocketInboundChannelAdapter 仅依赖于原始的 PassThruSubProtocolHandler 实现,该实现将 WebSocketMessage 转换为 Message

WebSocketInboundChannelAdapter 只接受并发送给底层集成流(integration flow)拥有 SimpMessageType.MESSAGE 或空的 simpMessageType 头的 Message 实例。所有其他 Message 类型通过由 SubProtocolHandler 实现(例如 StompSubProtocolHandler)发出的 ApplicationEvent 实例处理。

在服务器端,如果存在 @EnableWebSocketMessageBroker 配置,您可以将 WebSocketInboundChannelAdapter 配置为启用 useBroker = true 选项。在这种情况下,所有 non-MESSAGE 类型的 Message 将被委托给提供的 AbstractBrokerMessageHandler 处理。此外,如果 Broker 中继(broker relay)配置了目标前缀,那些与 Broker 目标匹配的消息将被路由到 AbstractBrokerMessageHandler,而不是 WebSocketInboundChannelAdapteroutputChannel

如果 useBroker = false 且接收到的消息是 SimpMessageType.CONNECT 类型,WebSocketInboundChannelAdapter 会立即向 WebSocketSession 发送 SimpMessageType.CONNECT_ACK 消息,而不会将其发送到通道。

Spring 的 WebSocket 支持只允许配置一个 Broker 中继(broker relay)。因此,我们不需要 AbstractBrokerMessageHandler 引用。它会在 Application Context 中被检测到。

有关更多配置选项,请参阅 WebSockets 命名空间支持

WebSocket 出站通道适配器

WebSocketOutboundChannelAdapter

  1. 接受来自其 MessageChannel 的 Spring Integration 消息

  2. MessageHeaders 中确定 WebSocketSession 的 id

  3. 从提供的 IntegrationWebSocketContainer 中检索 WebSocketSession

  4. WebSocketMessage 的转换和发送工作委托给提供的 SubProtocolHandlerRegistry 中相应的 SubProtocolHandler

在客户端,不需要 WebSocketSession id 消息头,因为 ClientWebSocketContainer 只处理单个连接及其对应的 WebSocketSession

要使用 STOMP 子协议,您应该使用 StompSubProtocolHandler 配置此适配器。然后,您可以使用 StompHeaderAccessor.create(StompCommand…​)MessageBuilder,或者仅仅使用 HeaderEnricher(请参阅 Header Enricher),将任何 STOMP 消息类型发送到此适配器。

本章的其余部分主要介绍其他配置选项。

WebSockets 命名空间支持

Spring Integration WebSocket 命名空间包含本章其余部分描述的几个组件。要将其包含在您的配置中,请在您的应用程序上下文配置文件中使用以下命名空间声明

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:int="http://www.springframework.org/schema/integration"
  xmlns:int-websocket="http://www.springframework.org/schema/integration/websocket"
  xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    https://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/integration
    https://www.springframework.org/schema/integration/spring-integration.xsd
    http://www.springframework.org/schema/integration/websocket
    https://www.springframework.org/schema/integration/websocket/spring-integration-websocket.xsd">
    ...
</beans>

<int-websocket:client-container> 属性

以下列表显示了 <int-websocket:client-container> 元素的可用属性

<int-websocket:client-container
                  id=""                             (1)
                  client=""                         (2)
                  uri=""                            (3)
                  uri-variables=""                  (4)
                  origin=""                         (5)
                  send-time-limit=""                (6)
                  send-buffer-size-limit=""         (7)
                  send-buffer-overflow-strategy=""  (8)
                  auto-startup=""                   (9)
                  phase="">                        (10)
                <int-websocket:http-headers>
                  <entry key="" value=""/>
                </int-websocket:http-headers>      (11)
</int-websocket:client-container>
1 组件 bean 名称。
2 WebSocketClient bean 引用。
3 目标 WebSocket 服务的 uriuriTemplate。如果将其用作带有 URI 变量占位符的 uriTemplate,则 uri-variables 属性是必需的。
4 uri 属性值中 URI 变量占位符的逗号分隔值。这些值根据其在 uri 中的顺序替换到占位符中。请参阅 UriComponents.expand(Object…​uriVariableValues)
5 Origin 握手 HTTP 头值。
6 WebSocket 会话的“发送”超时限制。默认为 10000
7 WebSocket 会话的“发送”消息大小限制。默认为 524288
8 WebSocket 会话发送缓冲区溢出策略,用于确定会话的出站消息缓冲区达到 send-buffer-size-limit 时的行为。有关可能的值和更多详细信息,请参阅 ConcurrentWebSocketSessionDecorator.OverflowStrategy
9 布尔值,指示此端点是否应自动启动。默认为 false,假定此容器是从 WebSocket 入站适配器 启动的。
10 此端点应在其内部启动和停止的生命周期阶段。值越低,此端点启动越早,停止越晚。默认为 Integer.MAX_VALUE。值可以是负数。请参阅 SmartLifeCycle
11 用于握手请求的 HttpHeaders Map。

<int-websocket:server-container> 属性

以下列表显示了 <int-websocket:server-container> 元素的可用属性

<int-websocket:server-container
          id=""                             (1)
          path=""                           (2)
          handshake-handler=""              (3)
          handshake-interceptors=""         (4)
          decorator-factories=""            (5)
          send-time-limit=""                (6)
          send-buffer-size-limit=""         (7)
          send-buffer-overflow-strategy=""  (8)
          allowed-origins="">               (9)
          <int-websocket:sockjs
            client-library-url=""          (10)
            stream-bytes-limit=""          (11)
            session-cookie-needed=""       (12)
            heartbeat-time=""              (13)
            disconnect-delay=""            (14)
            message-cache-size=""          (15)
            websocket-enabled=""           (16)
            scheduler=""                   (17)
            message-codec=""               (18)
            transport-handlers=""          (19)
            suppress-cors="true" />        (20)
</int-websocket:server-container>
1 组件 bean 名称。
2 将特定请求映射到 WebSocketHandler 的路径(或逗号分隔的路径)。支持精确路径映射 URI(例如 /myPath)和 ant 风格的路径模式(例如 /myPath/**)。
3 HandshakeHandler bean 引用。默认为 DefaultHandshakeHandler
4 HandshakeInterceptor bean 引用列表。
5 一个或多个工厂(WebSocketHandlerDecoratorFactory)的列表,用于装饰处理 WebSocket 消息的处理器。这对于某些高级用例可能很有用(例如,允许 Spring Security 在相应的 HTTP 会话过期时强制关闭 WebSocket 会话)。有关更多信息,请参阅 Spring Session 项目
6 请参阅 <int-websocket:client-container> 中的相同选项。
7 请参阅 <int-websocket:client-container> 中的相同选项。
8 WebSocket 会话发送缓冲区溢出策略,用于确定会话的出站消息缓冲区达到 send-buffer-size-limit 时的行为。有关可能的值和更多详细信息,请参阅 ConcurrentWebSocketSessionDecorator.OverflowStrategy
9 允许的 origin 头值。您可以指定多个 origin 作为逗号分隔列表。此检查主要针对浏览器客户端设计。没有任何东西能阻止其他类型的客户端修改 origin 头值。当启用 SockJS 并限制允许的 origin 时,不使用 origin 头进行跨域请求的传输类型(jsonp-pollingiframe-xhr-pollingiframe-eventsourceiframe-htmlfile)将被禁用。因此,不支持 IE6 和 IE7,IE8 和 IE9 仅在不使用 cookie 的情况下支持。默认情况下,允许所有 origin。
10 没有原生跨域通信的传输方式(例如 eventsourcehtmlfile)必须在不可见的 iframe 中从“外部”域获取一个简单页面,以便 iframe 中的代码可以在 SockJS 服务器本地的域中运行。由于 iframe 需要加载 SockJS JavaScript 客户端库,此属性允许您指定加载位置。默认情况下,它指向 d1fxtkz8shb9d2.cloudfront.net/sockjs-0.3.4.min.js。但是,您也可以将其设置为指向由应用程序提供的 URL。请注意,可以指定相对 URL,在这种情况下,该 URL 必须相对于 iframe URL。例如,假设 SockJS 端点映射到 /sockjs,生成的 iframe URL 为 /sockjs/iframe.html,则相对 URL 必须以 ../../ 开头,才能向上遍历到 SockJS 映射上层的位置。对于基于前缀的 servlet 映射,可能需要多一层遍历。
11 在关闭之前,单个 HTTP 流请求可以发送的最小字节数。默认为 128K(即 128*1024 或 131072 字节)。
12 SockJs /info 端点响应中的 cookie_needed 值。此属性指示应用程序是否需要 JSESSIONID cookie 才能正常运行(例如,用于负载均衡或 Java Servlet 容器中的 HTTP 会话使用)。
13 服务器在未发送任何消息后经过一段时间(以毫秒为单位),应向客户端发送心跳帧以保持连接不中断。默认值为 25,000(25 秒)。
14 在没有接收连接(即服务器可以通过其向客户端发送数据的活动连接)后,客户端被视为断开连接的时间(以毫秒为单位)。默认值为 5000
15 会话在等待客户端的下一个 HTTP 轮询请求时可以缓存的服务器到客户端消息的数量。默认大小为 100
16 一些负载均衡器不支持 WebSockets。将此选项设置为 false 可在服务器端禁用 WebSocket 传输。默认值为 true
17 TaskScheduler bean 引用。如果未提供值,则会创建一个新的 ThreadPoolTaskScheduler 实例。此调度器实例用于调度心跳消息。
18 SockJsMessageCodec bean 引用,用于编码和解码 SockJS 消息。默认使用 Jackson2SockJsMessageCodec,这要求 classpath 中存在 Jackson 库。
19 TransportHandler bean 引用列表。
20 是否禁用为 SockJS 请求自动添加 CORS 头。默认值为 false

<int-websocket:outbound-channel-adapter> 属性

以下列表显示了 <int-websocket:outbound-channel-adapter> 元素的可用属性

<int-websocket:outbound-channel-adapter
                          id=""                             (1)
                          channel=""                        (2)
                          container=""                      (3)
                          default-protocol-handler=""       (4)
                          protocol-handlers=""              (5)
                          message-converters=""             (6)
                          merge-with-default-converters=""  (7)
                          auto-startup=""                   (8)
                          phase=""/>                        (9)
1 组件 bean 名称。如果您未提供 channel 属性,则会创建一个 DirectChannel 并以 id 属性作为 bean 名称注册到应用程序上下文中。在这种情况下,端点会以 id 加上 .adapter 作为 bean 名称进行注册。并且 MessageHandler 会以 id 加上 .handler 作为 bean 别名进行注册。
2 标识附加到此适配器的通道。
3 IntegrationWebSocketContainer bean 的引用,它封装了底层连接和 WebSocketSession 处理操作。必需。
4 可选的 SubProtocolHandler 实例引用。当客户端未请求子协议或只有一个协议处理器时使用。如果未提供此引用或 protocol-handlers 列表,则默认使用 PassThruSubProtocolHandler
5 此通道适配器的 SubProtocolHandler bean 引用列表。如果您只提供一个 bean 引用且未提供 default-protocol-handler,则该单个 SubProtocolHandler 将用作 default-protocol-handler。如果您未设置此属性或 default-protocol-handler,则默认使用 PassThruSubProtocolHandler
6 此通道适配器的 MessageConverter bean 引用列表。
7 布尔值,指示是否应在任何自定义转换器之后注册默认转换器。仅在提供了 message-converters 时使用此标志。否则,将注册所有默认转换器。默认为 false。默认转换器按顺序为:StringMessageConverterByteArrayMessageConverterMappingJackson2MessageConverter(如果 classpath 中存在 Jackson 库)。
8 布尔值,指示此端点是否应自动启动。默认为 true
9 此端点应在其内部启动和停止的生命周期阶段。值越低,此端点启动越早,停止越晚。默认为 Integer.MIN_VALUE。值可以是负数。请参阅 SmartLifeCycle

<int-websocket:inbound-channel-adapter> 属性

以下列表显示了 <int-websocket:outbound-channel-adapter> 元素的可用属性

<int-websocket:inbound-channel-adapter
                            id=""  (1)
                            channel=""  (2)
                            error-channel=""  (3)
                            container=""  (4)
                            default-protocol-handler=""  (5)
                            protocol-handlers=""  (6)
                            message-converters=""  (7)
                            merge-with-default-converters=""  (8)
                            send-timeout=""  (9)
                            payload-type=""  (10)
                            use-broker=""  (11)
                            auto-startup=""  (12)
                            phase=""/>  (13)
1 组件 bean 名称。如果您未设置 channel 属性,则会创建一个 DirectChannel 并以 id 属性作为 bean 名称注册到应用程序上下文中。在这种情况下,端点会以 id 加上 .adapter 作为 bean 名称进行注册。
2 标识附加到此适配器的通道。
3 ErrorMessage 实例应发送到的 MessageChannel bean 引用。
4 请参阅 <int-websocket:outbound-channel-adapter> 中的相同选项。
5 请参阅 <int-websocket:outbound-channel-adapter> 中的相同选项。
6 请参阅 <int-websocket:outbound-channel-adapter> 中的相同选项。
7 请参阅 <int-websocket:outbound-channel-adapter> 中的相同选项。
8 请参阅 <int-websocket:outbound-channel-adapter> 中的相同选项。
9 如果通道可能阻塞,发送消息到通道时等待的最长时间(以毫秒为单位)。例如,如果 QueueChannel 的最大容量已满,它可能会阻塞直到有空间可用。
10 从传入的 WebSocketMessage 转换的目标载荷(payload)的 Java 类型完全限定名。默认为 java.lang.String
11 指示此适配器是否将 non-MESSAGE 类型的 WebSocketMessage 实例和具有 Broker 目标的消息发送到应用程序上下文中的 AbstractBrokerMessageHandler。当此属性为 true 时,需要 Broker 中继(Broker Relay)配置。此属性仅在服务器端使用。在客户端,此属性被忽略。默认为 false
12 请参阅 <int-websocket:outbound-channel-adapter> 中的相同选项。
13 请参阅 <int-websocket:outbound-channel-adapter> 中的相同选项。

使用 ClientStompEncoder

从版本 4.3.13 开始,Spring Integration 提供了 ClientStompEncoder(作为标准 StompEncoder 的扩展),用于 WebSocket 通道适配器的客户端。为了正确进行客户端消息准备,您必须将 ClientStompEncoder 的实例注入到 StompSubProtocolHandler 中。默认的 StompSubProtocolHandler 有一个问题,它是为服务器端设计的,因此它会将 SEND stompCommand 头更新为 MESSAGE(这是 STOMP 协议对服务器端的要求)。如果客户端不以正确的 SEND web socket 帧发送其消息,某些 STOMP Broker 不会接受它们。在这种情况下,ClientStompEncoder 的作用是在将消息编码为 byte[] 之前,覆盖 stompCommand 头并将其设置为 SEND 值。

动态 WebSocket 端点注册

从版本 5.5 开始,WebSocket 服务器端点(基于 ServerWebSocketContainer 的通道适配器)现在可以在运行时注册(和移除)— ServerWebSocketContainer 映射的 paths 通过 HandlerMapping 暴露到 DispatcherServlet 中,并对 WebSocket 客户端可见。动态和运行时集成流 支持有助于以透明的方式注册这些端点

@Autowired
IntegrationFlowContext integrationFlowContext;

@Autowired
HandshakeHandler handshakeHandler;
...
ServerWebSocketContainer serverWebSocketContainer =
       new ServerWebSocketContainer("/dynamic")
               .setHandshakeHandler(this.handshakeHandler);

WebSocketInboundChannelAdapter webSocketInboundChannelAdapter =
       new WebSocketInboundChannelAdapter(serverWebSocketContainer);

QueueChannel dynamicRequestsChannel = new QueueChannel();

IntegrationFlow serverFlow =
       IntegrationFlow.from(webSocketInboundChannelAdapter)
               .channel(dynamicRequestsChannel)
               .get();

IntegrationFlowContext.IntegrationFlowRegistration dynamicServerFlow =
       this.integrationFlowContext.registration(serverFlow)
               .addBean(serverWebSocketContainer)
               .register();
...
dynamicServerFlow.destroy();
在动态流注册上调用 .addBean(serverWebSocketContainer) 非常重要,以便将 ServerWebSocketContainer 实例添加到 ApplicationContext 中用于端点注册。当动态流注册被销毁时,相关的 ServerWebSocketContainer 实例也会被销毁,相应的端点注册(包括 URL 路径映射)也是如此。
动态 Websocket 端点只能通过 Spring Integration 机制注册:当使用常规的 Spring @EnableWebsocket 时,Spring Integration 配置会退出,并且不会注册用于动态端点的基础设施。