当前位置:首页 > 技术分析 > 正文内容

Spring Boot3 中 WebSocket 实现数据实时通信全解析

ruisui883个月前 (03-17)技术分析13

各位互联网大厂的开发同仁们,在如今的互联网应用开发中,实时通信功能越来越重要。比如在线聊天、数据推送、实时通知等场景,都离不开高效的实时通信技术。而 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 实现数据实时通信。各位开发小伙伴们,赶紧在自己的项目中实践起来吧!

扫描二维码推送至手机访问。

版权声明:本文由ruisui88发布,如需转载请注明出处。

本文链接:http://www.ruisui88.com/post/2820.html

分享给朋友:

“Spring Boot3 中 WebSocket 实现数据实时通信全解析” 的相关文章

亚马逊推出 Amazon Linux 2023 发行版,专为 AWS 云进行优化

稿源:IT之家3 月 19 日消息,本周早些时候,亚马逊宣布推出其第三代 Linux 发行版 Amazon Linux 2023(AL2023)。亚马逊表示,该版本将带来高安全性标准、可预测的生命周期和确定性更新。Amazon Linux 2023 针对 Amazon EC2 进行了优化,与最新的...

用IDEA开发如何用Git快速拉取指定分支代码?

1,准备空的文件夹,git init2,关联远程仓库,git remote add origin gitlab地址3,拉取远程分支代码,git pull origin 远程分支名再用IDEA打开项目即可...

面试被逼疯:聊聊Python Import System?

面试官一个小时逼疯面试者:聊聊Python Import System?对于每一位Python开发者来说,import这个关键字是再熟悉不过了,无论是我们引用官方库还是三方库,都可以通过import xxx的形式来导入。可能很多人认为这只是Python的一个最基础的常识之一,似乎没有可以扩展的点了,...

一次Java内存占用高的排查案例,解释了我对内存问题的所有疑问

问题现象7月25号,我们一服务的内存占用较高,约13G,容器总内存16G,占用约85%,触发了内存报警(阈值85%),而我们是按容器内存60%(9.6G)的比例配置的JVM堆内存。看了下其它服务,同样的堆内存配置,它们内存占用约70%~79%,此服务比其它服务内存占用稍大。那为什么此服务内存占用稍大...

再来一波黑科技工具,低调使用

静读天下静读天下是一个特别优秀的电子书阅读器。它上面有多个在线书库,像古登堡计划,很多种优秀的书杂志,都可以下载来阅读。它还能智能识别章节功能,还支持外置的语音阅读功能。它支持多种文本格式,比如说txt,pdf,epub,mobi等等。为了便于阅读它还有10 种配色方式,还有夜间模式。不过免费版有广...

《暗黑破坏神 2:重制版》PC 版 2.3 版本发布,支持英伟达 DLSS

IT之家 12 月 3 日消息,暴雪为《暗黑破坏神 2:重制版》PC 版发布了更新 2.3 版本,添加了“离线难度缩放”滑块(玩家可以在单人游戏时增加挑战和奖励的级别)、多项辅助功能和用户界面改进,以及英伟达 DLSS 支持。玩法改进:玩家现在可以在离线游戏的选项菜单中使用“游戏难度等级”,它提供与...