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

启用 STOMP

STOMP over WebSocket 支持在spring-messagingspring-websocket模块。一旦你有了这些依赖关系,你就可以公开一个 STOMP endpoint over WebSocket,如以下示例所示: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)所到的端点的 HTTP URL 客户端需要连接才能进行 WebSocket 握手。
2 目标标头以/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 Fallbackregistry.addEndpoint("/portfolio").withSockJS()在 JavaScript 方面, 通过遵循这些说明spring-doc.cadn.net.cn

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

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