对于最新稳定版本,请使用 Spring Framework 7.0.6spring-doc.cadn.net.cn

外部代理

简单代理非常适合入门使用,但它仅支持部分 STOMP 命令(不支持 ack、receipts 以及其他一些特性),依赖于一个简单的消息发送循环,并且不适合用于集群环境。作为替代方案,您可以升级应用程序以使用功能完备的消息代理。spring-doc.cadn.net.cn

请参阅您所选消息代理(例如 RabbitMQActiveMQ 等)的 STOMP 文档,安装该代理, 并启用 STOMP 支持来运行它。然后,您可以在 Spring 配置中启用 STOMP 代理中继 (而不是简单代理)。spring-doc.cadn.net.cn

以下示例配置启用了一个功能齐全的代理(broker):spring-doc.cadn.net.cn

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

	@Override
	public void registerStompEndpoints(StompEndpointRegistry registry) {
		registry.addEndpoint("/portfolio").withSockJS();
	}

	@Override
	public void configureMessageBroker(MessageBrokerRegistry registry) {
		registry.enableStompBrokerRelay("/topic", "/queue");
		registry.setApplicationDestinationPrefixes("/app");
	}

}

以下示例展示了与前述示例等效的 XML 配置:spring-doc.cadn.net.cn

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:websocket="http://www.springframework.org/schema/websocket"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans
		https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/websocket
		https://www.springframework.org/schema/websocket/spring-websocket.xsd">

	<websocket:message-broker application-destination-prefix="/app">
		<websocket:stomp-endpoint path="/portfolio" />
			<websocket:sockjs/>
		</websocket:stomp-endpoint>
		<websocket:stomp-broker-relay prefix="/topic,/queue" />
	</websocket:message-broker>

</beans>

前述配置中的 STOMP 代理中继是一个 Spring MessageHandler ,它通过将消息转发到外部消息代理来处理消息。 为此,它会与代理建立 TCP 连接,将所有消息转发给代理, 然后通过客户端的 WebSocket 会话将从代理接收到的所有消息转发给客户端。 本质上,它充当一个在两个方向上转发消息的“中继”。spring-doc.cadn.net.cn

为 TCP 连接管理,在您的项目中添加 io.projectreactor.netty:reactor-nettyio.netty:netty-all 依赖项。

此外,应用程序组件(例如 HTTP 请求处理方法、业务服务等)也可以向代理中继发送消息,如发送消息一节所述,以向已订阅的 WebSocket 客户端广播消息。spring-doc.cadn.net.cn

实际上,代理中继(broker relay)能够实现强大且可扩展的消息广播。spring-doc.cadn.net.cn