Spring Boot整合STOMP实现实时通信
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");
}
}
这段代码配置了Spring Boot中的WebSocket消息代理,使得客户端能够通过WebSocket连接到服务器,并使用STOMP协议来发送和接收消息。registerStompEndpoints
方法注册了一个WebSocket端点/ws
,并且指示使用SockJS来兼容不支持WebSocket的浏览器。configureMessageBroker
方法配置了一个简单的消息代理用于转发消息,并设置了应用程序的目的地前缀为/app
。这样,客户端可以通过/app
发送消息,服务器通过/topic
接收并转发消息。
评论已关闭