|
对于最新的稳定版本,请使用 Spring Framework 7.0.6! |
外部消息代理
简单代理非常适合入门,但仅支持STOMP命令的一个子集(它不支持确认、回执和其他一些功能),依赖于一个简单的消息发送循环,并且不适合集群。 作为替代方案,您可以升级您的应用程序以使用功能齐全的消息代理。
请参阅您选择的消息代理的STOMP文档(例如 RabbitMQ, ActiveMQ和其他),安装代理, 并以启用STOMP支持的方式运行它。然后您可以在Spring配置中启用STOMP代理中继 (而不是简单代理)。
以下示例配置启用了功能齐全的消息代理:
@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配置等价写法:
<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会话将从代理接收到的所有消息转发给客户端。本质上,它作为一个“中继”在两个方向上转发消息。
添加 io.projectreactor.netty:reactor-netty 和 io.netty:netty-all
依赖项以管理TCP连接。 |
此外,应用程序组件(如HTTP请求处理方法、业务服务等)也可以按照 发送消息 中所述,向代理中继发送消息,以向订阅的WebSocket客户端广播消息。
实际上,代理中继实现了健壮且可扩展的消息广播。