Springboot+WebSocket实现消息推送
以下是一个使用Spring Boot和WebSocket实现消息推送的简单示例:
- 添加依赖到你的
pom.xml
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
- 配置WebSocket:
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");
}
}
- 创建控制器来处理WebSocket消息:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
@Controller
public class WebSocketController {
@Autowired
private SimpMessagingTemplate simpMessagingTemplate;
@MessageMapping("/sendMessage")
public void sendMessage(String message) {
simpMessagingTemplate.convertAndSend("/topic/public", message);
}
}
- 前端JavaScript代码来连接WebSocket并接收消息:
var socket = new SockJS('/ws');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/public', function (message) {
showMessage(JSON.parse(message.body).content);
});
});
function showMessage(message) {
var messageElement = document.createElement('p');
messageElement.textContent = message;
document.getElementById('messages').appendChild(messageElement);
}
确保你的Spring Boot应用程序已经启动,并且前端JavaScript代码在一个HTML页面上运行。当你发送一个消息到/sendMessage
端点时,所有连接到/topic/public
的客户端都会收到这个消息。
评论已关闭