跳到主要内容
版本:7.0.3

启用STOMP

Hunyuan 7b 中英对照 Enable STOMP

spring-messagingspring-websocket模块提供了对STOMP协议的支持。一旦你添加了这些依赖,就可以通过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");
}
}
备注

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

要通过浏览器连接STOMP,可以使用stomp-js/stompjs,这是维护最为活跃的JavaScript库。

以下示例代码就是基于它的:

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

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

请注意,在前面的示例中,stompClient不需要指定loginpasscode头信息。即使指定了,这些信息在服务器端也会被忽略(或者更确切地说,会被覆盖)。有关身份验证的更多信息,请参阅连接到Broker身份验证

更多示例代码请参见: