外部 Broker

简单 Broker 非常适合入门,但它只支持 STOMP 命令的子集(不支持 ack、receipts 和一些其他特性),依赖于简单的消息发送循环,并且不适合集群。作为替代方案,你可以升级你的应用,使用功能齐全的消息 Broker。

请查阅你选择的消息 Broker 的 STOMP 文档(例如 RabbitMQActiveMQ 等),安装并运行 Broker,并启用 STOMP 支持。然后在 Spring 配置中启用 STOMP Broker 中继(而不是简单 Broker)。

以下示例配置启用了一个功能齐全的 Broker

  • Java

  • Kotlin

  • Xml

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration 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");
	}

}
@Configuration
@EnableWebSocketMessageBroker
class WebSocketConfiguration : WebSocketMessageBrokerConfigurer {

	override fun registerStompEndpoints(registry: StompEndpointRegistry) {
		registry.addEndpoint("/portfolio").withSockJS()
	}

	override fun configureMessageBroker(registry: MessageBrokerRegistry) {
		registry.enableStompBrokerRelay("/topic", "/queue")
		registry.setApplicationDestinationPrefixes("/app")
	}
}
<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 Broker 中继是一个 Spring MessageHandler,它通过将消息转发到外部消息 Broker 来处理消息。为此,它建立到 Broker 的 TCP 连接,将所有消息转发给 Broker,然后将从 Broker 收到的所有消息通过 WebSocket 会话转发给客户端。本质上,它充当一个双向转发消息的“中继”。

请为你的项目添加 io.projectreactor.netty:reactor-nettyio.netty:netty-all 依赖项,以便进行 TCP 连接管理。

此外,应用组件(例如 HTTP 请求处理方法、业务服务等)也可以向 Broker 中继发送消息,如 发送消息 中所述,以便向已订阅的 WebSocket 客户端广播消息。

实际上,Broker 中继实现了健壮且可扩展的消息广播。