启用STOMP
spring-messaging和spring-websocket模块提供了对STOMP协议的支持。一旦你添加了这些依赖,就可以通过WebSocket暴露一个STOMP端点,如下例所示:
- Java
- Kotlin
- Xml
@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");
}
}
@Configuration
@EnableWebSocketMessageBroker
class WebSocketConfiguration : WebSocketMessageBrokerConfigurer {
override fun registerStompEndpoints(registry: StompEndpointRegistry) {
// /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 fun configureMessageBroker(config: MessageBrokerRegistry) {
// 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")
}
}
<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>
备注
对于内置的简单代理(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 端则可以按照 这些说明 进行配置。
更多示例代码请参见:
- 使用WebSocket构建交互式Web应用程序——入门指南。
- 股票投资组合——一个示例应用程序。