跳到主要内容

启用 STOMP

ChatGPT-4o-mini 中英对照 Enable STOMP

STOMP over WebSocket 支持在 spring-messagingspring-websocket 模块中可用。一旦你有了这些依赖项,你可以通过 WebSocket 暴露一个 STOMP 端点,如下例所示:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
// /portfolio is the HTTP URL for the endpoint to which a WebSocket (or SockJS)
// client needs to connect for the WebSocket handshake
registry.addEndpoint("/portfolio");
}

@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
// STOMP messages whose destination header begins with /app are routed to
// @MessageMapping methods in @Controller classes
config.setApplicationDestinationPrefixes("/app");
// Use the built-in message broker for subscriptions and broadcasting and
// route messages whose destination header begins with /topic or /queue to the broker
config.enableSimpleBroker("/topic", "/queue");
}
}
java
备注

对于内置的简单代理,/topic/queue 前缀没有任何特殊含义。它们仅仅是一种约定,用于区分发布-订阅与点对点消息传递(即,多个订阅者与一个消费者)。当你使用外部代理时,请查看该代理的 STOMP 页面,以了解它支持什么类型的 STOMP 目标和前缀。

要从浏览器连接,对于 STOMP,您可以使用 stomp-js/stompjs,这是一个最活跃维护的 JavaScript 库。

以下示例代码基于此:

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

或者,如果您通过 SockJS 连接,您可以在服务器端启用 SockJS Fallback,使用 registry.addEndpoint("/portfolio").withSockJS(),在 JavaScript 端,按照 这些说明 操作。

注意,在前面的示例中,stompClient 不需要指定 loginpasscode 头。即使指定了,它们也会在服务器端被忽略(或者说,被覆盖)。有关身份验证的更多信息,请参见 Connecting to a BrokerAuthentication

有关更多示例代码,请参见: