Order of Messages

消息从代理发布到 clientOutboundChannel,从那里它们写到了 WebSocket 会话中。由于该通道由 ThreadPoolExecutor 支持,消息会在不同的线程中处理,并且客户端接收到的结果序列可能与准确的发布顺序不匹配。

要启用有序发布,请按如下所示设置 setPreservePublishOrder 标志:

  • Java

  • Kotlin

  • Xml

@Configuration
@EnableWebSocketMessageBroker
public class PublishOrderWebSocketConfiguration implements WebSocketMessageBrokerConfigurer {

	@Override
	public void configureMessageBroker(MessageBrokerRegistry registry) {
		// ...
		registry.setPreservePublishOrder(true);
	}

}
@Configuration
@EnableWebSocketMessageBroker
class PublishOrderWebSocketConfiguration : WebSocketMessageBrokerConfigurer {

	override fun configureMessageBroker(registry: MessageBrokerRegistry) {
		// ...
		registry.setPreservePublishOrder(true)
	}
}
<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 preserve-publish-order="true">
		<!-- ... -->
	</websocket:message-broker>

</beans>

当设置了该标志时,同一个客户端会话中的消息一次一个发布到 clientOutboundChannel 中,从而确保了发布的顺序。请注意,这会产生较小的性能开销,因此仅在需要时才应启用它。

同样也适用于从客户端的消息,它们被发送到 clientInboundChannel 中,从那里根据它们的目的地前缀来处理它们。由于该通道由 ThreadPoolExecutor 支持,消息会在不同的线程中处理,并且处理的结果序列可能与它们收到的准确顺序不匹配。

要启用有序发布,请按如下所示设置 setPreserveReceiveOrder 标志:

  • Java

  • Kotlin

@Configuration
@EnableWebSocketMessageBroker
public class ReceiveOrderWebSocketConfiguration implements WebSocketMessageBrokerConfigurer {

	@Override
	public void registerStompEndpoints(StompEndpointRegistry registry) {
		registry.setPreserveReceiveOrder(true);
	}
}
@Configuration
@EnableWebSocketMessageBroker
class ReceiveOrderWebSocketConfiguration : WebSocketMessageBrokerConfigurer {

	override fun registerStompEndpoints(registry: StompEndpointRegistry) {
		registry.setPreserveReceiveOrder(true)
	}
}