要在Spring Boot中集成WebSocket實(shí)現(xiàn)消息推送,可以按照以下步驟進(jìn)行操作:
pom.xml
文件中添加以下依賴:<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
WebSocketConfigurer
接口,并實(shí)現(xiàn)registerWebSocketHandlers
方法。在該方法中,配置WebSocket處理器和攔截器。@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(myWebSocketHandler(), "/websocket").addInterceptors(new WebSocketInterceptor());
}
@Bean
public WebSocketHandler myWebSocketHandler() {
return new MyWebSocketHandler();
}
}
WebSocketHandler
接口,并重寫相應(yīng)的方法。public class MyWebSocketHandler extends TextWebSocketHandler {
private static final Set<WebSocketSession> sessions = Collections.synchronizedSet(new HashSet<>());
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
sessions.add(session);
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
// 處理收到的消息
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
sessions.remove(session);
}
}
HandshakeInterceptor
接口,并重寫相應(yīng)的方法。public class WebSocketInterceptor implements HandshakeInterceptor {
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
// 在握手前執(zhí)行操作
return true;
}
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
// 在握手后執(zhí)行操作
}
}
sendMessage
方法發(fā)送消息。@Autowired
private SimpMessagingTemplate messagingTemplate;
public void sendMessage(String message) {
messagingTemplate.convertAndSend("/topic/message", message);
}
以上步驟完成后,你就可以使用WebSocket在Spring Boot中實(shí)現(xiàn)消息推送了。在前端頁面中,可以使用JavaScript的new WebSocket(url)
創(chuàng)建WebSocket連接,并通過onmessage
事件接收到推送的消息。