Spring Boot3 中 WebSocket 实现数据实时通信全解析
各位互联网大厂的开发同仁们,在如今的互联网应用开发中,实时通信功能越来越重要。比如在线聊天、数据推送、实时通知等场景,都离不开高效的实时通信技术。而 WebSocket 作为一种高效的双向通信协议,在 Spring Boot3 中能够被轻松整合,从而实现强大的数据实时通信功能。今天,咱们就一起来深入探究一下 Spring Boot3 中如何整合 WebSocket。
WebSocket 简介
WebSocket 是一种网络通信协议,它建立在 TCP 协议之上,与 HTTP 协议有良好的兼容性。其数据格式轻量,性能开销小,并且支持发送文本和二进制数据 ,关键是没有同源限制,客户端可与任意服务器通信。与传统 HTTP 请求 - 响应模式不同,它提供全双工通信通道,允许服务器主动向客户端推送数据,实现双向实时通信。
Spring Boot3 整合 WebSocket 步骤
添加依赖
对于 Spring Boot 项目,若使用内嵌应用容器,引入
spring-boot-starter-websocket依赖即可
org.springframework.boot
spring-boot-starter-websocket
若部署在独立容器中,如 Tomcat 或 Jetty 等,Spring Boot 假设 WebSocket 配置由容器负责。
配置 WebSocket
MVC 应用中的配置:在基于 Spring MVC 的应用里,创建一个 WebSocket 配置类并实现WebSocketConfigurer接口来注册自定义处理器。
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new CustomWebSocketHandler(), "/ws").setAllowedOrigins("*");
}
}
上述配置中,定义了 WebSocket 路径/ws用于客户端连接,CustomWebSocketHandler则用于处理 WebSocket 消息。
定义消息处理类:以简单的消息回显功能为例,创建CustomWebSocketHandler类
import org.springframework.web.socket.handler.TextWebSocketHandler;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
public class CustomWebSocketHandler extends TextWebSocketHandler {
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
String clientMessage = message.getPayload();
session.sendMessage(new TextMessage("echo: " + clientMessage));
}
}
该类继承TextWebSocketHandler,实现了将接收到的客户端消息回显给客户端的功能。
Reactive 应用中的 WebSocket 支持
在基于 Reactive 模式的应用中,Spring Boot 通过 WebFlux 提供 WebSocket 支持。需引入jakarta.websocket-api和
spring-boot-starter-webflux依赖。
org.springframework.boot
spring-boot-starter-webflux
jakarta.websocket
jakarta.websocket-api
其配置与 MVC 略有不同,可通过 router 函数配置 WebSocket 路径并定义处理器
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter;
import java.util.Map;
@Configuration
public class ReactiveWebSocketConfig {
@Bean
public SimpleUrlHandlerMapping webSocketMapping(CustomReactiveWebSocketHandler handler) {
return new SimpleUrlHandlerMapping(Map.of("/ws", handler), -1);
}
@Bean
public WebSocketHandlerAdapter handlerAdapter() {
return new WebSocketHandlerAdapter();
}
}
接着定义WebSocketHandler实现类处理消息
import org.springframework.web.reactive.socket.WebSocketHandler;
// 后续代码省略
测试 WebSocket 功能
启动 Spring Boot 应用:完成上述配置和代码编写后,启动 Spring Boot 应用。前端测试:编写简单的 HTML 页面测试 WebSocket 连接和消息收发。例如。
WebSocket测试
WebSocket测试页面
<script>
let ws = null;
function connect() {
ws = new WebSocket('ws://localhost:8080/ws');
ws.onopen = function () {
console.log('WebSocket连接已建立');
appendMessage('系统消息:连接已建立');
};
ws.onmessage = function (event) {
appendMessage('收到消息:' + event.data);
};
ws.onclose = function () {
console.log('WebSocket连接已关闭');
appendMessage('系统消息:连接已关闭');
};
ws.onerror = function (error) {
console.error('WebSocket错误:', error);
appendMessage('系统消息:连接发生错误');
};
}
function sendMessage() {
const messageInput = document.getElementById('messageInput');
const message = messageInput.value;
if (ws && message) {
ws.send(message);
appendMessage('发送消息:' + message);
messageInput.value = '';
}
}
function appendMessage(message) {
const messagesDiv = document.getElementById('messages');
const messageElement = document.createElement('div');
messageElement.textContent = message;
messagesDiv.appendChild(messageElement);
}
// 页面加载完成后连接WebSocket
window.onload = connect;
</script>
打开浏览器访问该 HTML 页面,在输入框输入消息点击发送,即可看到消息发送到服务端并回显回来。
总结
通过以上步骤,咱们就成功在 Spring Boot3 中整合了 WebSocket 实现数据实时通信。各位开发小伙伴们,赶紧在自己的项目中实践起来吧!