Order of Messages

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

Messages from the broker are published to the clientOutboundChannel, from where they are written to WebSocket sessions. As the channel is backed by a ThreadPoolExecutor, messages are processed in different threads, and the resulting sequence received by the client may not match the exact order of publication.

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

To enable ordered publishing, set the setPreservePublishOrder flag as follows:

@Configuration
@EnableWebSocketMessageBroker
public class PublishOrderWebSocketConfiguration implements WebSocketMessageBrokerConfigurer {

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

}

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

When the flag is set, messages within the same client session are published to the clientOutboundChannel one at a time, so that the order of publication is guaranteed. Note that this incurs a small performance overhead, so you should enable it only if it is required.

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

The same also applies to messages from the client, which are sent to the clientInboundChannel, from where they are handled according to their destination prefix. As the channel is backed by a ThreadPoolExecutor, messages are processed in different threads, and the resulting sequence of handling may not match the exact order in which they were received.

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

To enable ordered publishing, set the setPreserveReceiveOrder flag as follows:

@Configuration
@EnableWebSocketMessageBroker
public class ReceiveOrderWebSocketConfiguration implements WebSocketMessageBrokerConfigurer {

	@Override
	public void registerStompEndpoints(StompEndpointRegistry registry) {
		registry.setPreserveReceiveOrder(true);
	}
}