WebSocket的/topic/greetings主题何时及在何处创建?
关于/topic/greetings主题创建的说明
在Spring STOMP(搭配SockJS)的架构中,/topic/greetings这类主题不需要手动显式创建,它是由Spring内置的消息代理自动生成的,触发场景有两种:
- 当后端通过
@SendTo("/topic/greetings")注解向该主题发送消息时,如果主题尚未存在,消息代理会自动创建它; - 当前端调用
stompClient.subscribe('/topic/greetings')发起订阅请求时,若主题还未初始化,消息代理也会自动创建这个主题。
另外,你需要确保Spring配置类中开启了对/topic前缀主题的支持,通常配置如下:
@Configuration @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry config) { config.enableSimpleBroker("/topic"); // 允许处理/topic前缀的主题 config.setApplicationDestinationPrefixes("/app"); } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/gs-guide-websocket").withSockJS(); } }
这段配置里的enableSimpleBroker("/topic")是核心,它指定了消息代理要管理所有以/topic开头的主题,这也是/topic/greetings能被自动创建的前提。
你提供的代码参考
前端JS代码
function connect() { var socket = new SockJS('/gs-guide-websocket'); stompClient = Stomp.over(socket); stompClient.connect({}, function (frame) { setConnected(true); console.log('Connected: ' + frame); stompClient.subscribe('/topic/greetings', function (greeting) {//订阅该聊天频道 showGreeting(JSON.parse(greeting.body).content); }); }); }
后端Java代码
@Controller public class GreetingController { @MessageMapping("/hello") @SendTo("/topic/greetings") public Greeting greeting(HelloMessage message) throws Exception { return new Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!"); } }
内容的提问来源于stack exchange,提问作者shaxa 2000
相关产品推荐
相关产品推荐

