对于最新稳定版本,请使用 Spring Framework 7.0.6spring-doc.cadn.net.cn

启用 STOMP

STOMP over WebSocket 的支持包含在 spring-messagingspring-websocket 模块中。一旦你添加了这些依赖项,就可以通过 WebSocket 公开一个 STOMP 端点,如下例所示:spring-doc.cadn.net.cn

import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

	@Override
	public void registerStompEndpoints(StompEndpointRegistry registry) {
		registry.addEndpoint("/portfolio"); (1)
	}

	@Override
	public void configureMessageBroker(MessageBrokerRegistry config) {
		config.setApplicationDestinationPrefixes("/app"); (2)
		config.enableSimpleBroker("/topic", "/queue"); (3)
	}
}
1 /portfolio 是 WebSocket(或 SockJS)客户端为进行 WebSocket 握手而需要连接的端点的 HTTP URL。
2 目标地址(destination)头部以 /app 开头的 STOMP 消息会被路由到 @MessageMapping 类中的 @Controller 方法。
3 使用内置的消息代理处理订阅和广播,并将目标头(destination header)以 /topic/queue 开头的消息路由到该代理。

以下示例展示了与前述示例等效的 XML 配置:spring-doc.cadn.net.cn

<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:simple-broker prefix="/topic, /queue"/>
	</websocket:message-broker>

</beans>
对于内置的简单代理(simple broker),/topic/queue 前缀没有任何特殊含义。它们只是一种约定,用于区分发布-订阅(pub-sub)模式与点对点(point-to-point)消息传递(即多个订阅者与单一消费者)。当你使用外部代理时,请查阅该代理的 STOMP 页面,以了解它支持哪些类型的 STOMP 目标地址和前缀。

要从浏览器连接以使用 STOMP,您可以使用 stomp-js/stompjs,这是目前维护最积极的 JavaScript 库。spring-doc.cadn.net.cn

以下示例代码基于它编写:spring-doc.cadn.net.cn

const stompClient = new StompJs.Client({
       brokerURL: 'ws://domain.com/portfolio',
       onConnect: () => {
           // ...
       }
   });

或者,如果你通过 SockJS 进行连接,可以在服务器端通过 xref page 启用 SockJS 回退机制,并在 JavaScript 端按照 这些说明进行操作。spring-doc.cadn.net.cn

请注意,上例中的 stompClient 无需指定 loginpasscode 头部。即使指定了,这些头部也会在服务器端被忽略(更准确地说,会被覆盖)。有关认证的更多信息,请参阅连接到代理认证spring-doc.cadn.net.cn

更多示例代码请参见:spring-doc.cadn.net.cn