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