外部经纪人
简单的代理非常适合入门,但仅支持 STOMP 命令的一个子集(不支持 acks、receipts 和其他一些功能),依赖于简单的消息发送循环,并且不适合集群。作为替代方案,您可以将应用程序升级为使用功能齐全的消息代理。
以下示例配置启用一个功能齐全的代理:
- 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 代理中继是一个 Spring MessageHandler,它通过将消息转发到外部消息代理来处理消息。为此,它建立与代理的 TCP 连接,将所有消息转发给它,然后通过客户端的 WebSocket 会话将从代理接收到的所有消息转发给客户端。本质上,它充当一个“中继”,在两个方向上转发消息。
备注
将 io.projectreactor.netty:reactor-netty
和 io.netty:netty-all
依赖项添加到您的项目中,以进行 TCP 连接管理。
此外,应用程序组件(如 HTTP 请求处理方法、业务服务等)也可以向代理中继发送消息,如 发送消息 中所述,以向订阅的 WebSocket 客户端广播消息。
实际上,代理中继使得强大且可扩展的消息广播成为可能。