外部代理
簡單代理非常適合入門,但僅支援部分 STOMP 命令 (它不支援 acks、receipts 和其他一些功能),依賴簡單的訊息傳送迴圈,並且不適合叢集。作為替代方案,您可以升級您的應用程式以使用功能完整的訊息代理。
請參閱您選擇的訊息代理的 STOMP 文件 (例如 RabbitMQ、ActiveMQ 和其他),安裝代理,並在啟用 STOMP 支援的情況下執行它。然後,您可以在 Spring 組態中啟用 STOMP 代理中繼 (而不是簡單代理)。
以下範例組態啟用功能完整的代理
-
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 用戶端。
實際上,代理中繼實現了穩健且可擴展的訊息廣播。