【SOLUTION】Spring Boot 集成 WebSocket
    		       		warning:
    		            这篇文章距离上次修改已过424天,其中的内容可能已经有所变动。
    		        
        		                
                
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发送消息到服务端。
评论已关闭