外部代理

簡單代理非常適合入門,但它只支援 STOMP 命令的一個子集(不支援確認、回執和其他一些功能),依賴於簡單的訊息傳送迴圈,不適合叢集。作為替代方案,您可以升級您的應用程式以使用功能齊全的訊息代理。

請查閱您選擇的訊息代理(例如 RabbitMQActiveMQ 等)的 STOMP 文件,安裝代理,並啟用 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-nettyio.netty:netty-all 依賴項新增到您的專案中,用於 TCP 連線管理。

此外,應用程式元件(例如 HTTP 請求處理方法、業務服務等)也可以向代理中繼傳送訊息,如 傳送訊息 中所述,以向已訂閱的 WebSocket 客戶端廣播訊息。

實際上,代理中繼實現了健壯且可擴充套件的訊息廣播。

© . This site is unofficial and not affiliated with VMware.