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

启用STOMP

基于WebSocket的STOMP协议支持已在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 STOMP 消息的目标头以 /app 开头的将被路由到 @MessageMapping 方法中的 @Controller 类。
3 使用内置消息代理进行订阅和广播,并将目标头以/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>
对于内置的简单代理,/topic/queue 前缀没有任何特殊含义。它们仅仅是一种约定,用于区分发布订阅与点对点消息传递(即多个订阅者与一个消费者)。当你使用外部代理时,请检查代理的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连接,可以在服务器端启用 SockJS回退功能(设置 registry.addEndpoint("/portfolio").withSockJS()),并在JavaScript端按照 这些说明进行操作。spring-doc.cadn.net.cn

请注意,在前面的例子中,stompClient 不需要指定 loginpasscode 标头。即使指定了,它们也会在服务器端被忽略(或者更确切地说,被覆盖)。有关身份验证的更多信息,请参见 连接到代理身份验证spring-doc.cadn.net.cn

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