【SOLUTION】Spring Boot 集成 WebSocket
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.*;
@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
接口,并使用@EnableWebSocketMessageBroker
注解来启用Spring Boot的WebSocket消息代理功能。registerStompEndpoints
方法注册了一个WebSocket端点/ws
,并指示用SockJS解决方案提供Polling和其他传输。configureMessageBroker
方法配置了一个简单的消息代理用于广播,并设置了应用程序的目的地前缀为/app
。这样,客户端可以通过/topic/destination
接收广播消息,通过/app/destination
发送消息到服务端。
评论已关闭