import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic");
registry.setApplicationDestinationPrefixes("/app");
}
}
这段代码定义了一个配置类WebSocketConfig
,该类实现了WebSocketMessageBrokerConfigurer
接口。在registerStompEndpoints
方法中,我们注册了一个WebSocket端点/ws
,并且指示Spring使用SockJS。在configureMessageBroker
方法中,我们配置了一个简单的消息代理,监听/topic
目的地的消息,并指定所有应用程序目的地都以/app
为前缀。这样,客户端可以通过/topic/some.dest
接收广播消息,通过/app/some.dest
发送消息到服务器。