Springboot 整合 Websocket 轻松实现IM及时通讯
liuian 2025-07-17 20:40 3 浏览
一、方案实践
集成分为三步:添加依赖、增加配置类和消息核心类、前端集成。
1.1、添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.1.13.RELEASE</version>
</dependency>
1.2、增加WebSocket配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* WebSocket配置
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
1.3、增加消息核心类WebSocketServer
@ServerEndpoint("/websocket/{userId}")
@Component
@Slf4j
public class WebSocketServer {
// 消息存储
private static MessageStore messageStore;
// 消息发送
private static MessageSender messageSender;
public static void setMessageStore(MessageStore messageStore) {
WebSocketServer.messageStore = messageStore;
}
public static void setMessageSender(MessageSender messageSender) {
WebSocketServer.messageSender = messageSender;
}
/**
* 连接建立成功调用的方法
*/
@OnOpen
public void onOpen(Session session, @PathParam("userId") String userId) {
messageStore.saveSession(session);
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose(Session session, @PathParam("userId") String userId) {
messageStore.deleteSession(session);
}
/**
* 收到客户端消息后调用的方法
*
* @ Param message 客户端发送过来的消息
*/
@OnMessage
public void onMessage(String message, Session session) throws Exception {
log.warn("=========== 收到来自窗口" + session.getId() + "的信息:" + message);
handleTextMessage(session, new TextMessage(message));
}
/**
* @param session
* @param error
*/
@OnError
public void onError(Session session, @PathParam("userId") String userId, Throwable error) {
log.error("=========== 发生错误");
error.printStackTrace();
// msgStore.deleteSession(session);
}
public void handleTextMessage(Session session, TextMessage message) throws Exception {
log.warn("=========== Received message: {}", message.getPayload());
}
}
1.4、前端页面加入socket
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html">
<head>
<title>WebSocket Example</title>
</head>
<body>
登录用户ID:<input type="text" id="sendUserId" /></br>
接受用户ID:<input type="text" id="receivedUserId" /></br>
发送消息内容:<input type="text" id="messageInput" /></br>
接受消息内容:<input type="text" id="messageReceive" /></br>
<button onclick="sendMessage()">Send</button>
<script>
var socket = new WebSocket("ws://localhost:8080/websocket/aaa");
var roomId = "123456";
// 随机产出六位数字
var sendUserId = Math.floor(Math.random() * 1000000);
document.getElementById("sendUserId").value = sendUserId;
var messageReceive = document.getElementById("messageReceive");
socket.onopen = function (event) {
console.log("WebSocket is open now.");
let loginInfo = {
msgType: 2, //登录消息
sendUserId: sendUserId,
bizType: 1, //业务类型
bizOptModule: 1, //业务模块
roomId: roomId,
msgBody: {},
};
socket.send(JSON.stringify(loginInfo));
};
socket.onmessage = function (event) {
var message = event.data;
console.log("Received message: " + message);
messageReceive.value = message;
};
socket.onclose = function (event) {
console.log("WebSocket is closed now.");
};
function sendMessage() {
var message = document.getElementById("messageInput").value;
var receivedUserId = document.getElementById("receivedUserId").value;
let operateInfo = {
msgType: 100, //业务消息
sendUserId: sendUserId,
bizType: 1, //业务类型
bizOptModule: 1, //业务模块
roomId: roomId,
receivedUserId: receivedUserId,
msgBody: {
operateType: 1, //操作类型:禁言
operateContent: "1",
},
};
socket.send(JSON.stringify(operateInfo));
}
setInterval(() => {
socket.send("ping");
}, 30000);
</script>
</body>
</html>
二、小型及时通讯包含的模块
以上只是集成了Websocket框架,实现了基本的全双工通信,服务器和客户端都可以同时发送和接收数据。要想实现一些小型完整的即时通讯,还需要具备以下几个核心模块。架构图如下:
2.1、架构图
2.2、消息对象模型
组织消息内容,比如消息类型、发送者用户ID、接受者用户ID、具体的消息体等。比如:
public class SocketMsg<T> {
/**
* 消息类型:1心跳 2登录 3业务操作
*/
private Integer msgType;
/**
* 发送者用户ID
*/
private String sendUserId;
/**
* 接受者用户ID
*/
private String receivedUserId;
/**
* 业务类型
*/
private Integer bizType;
/**
* 业务操作模块
*/
private Integer bizOptModule;
/**
* 消息内容
*/
private T msgBody;
}
2.3、消息存储模块
负责存储消息内容、用户ID和sessionID的关系,防止数据丢失或者服务器重启等。
2.4、消息发送模块
功能开发完毕,一般部署到分布式集群环境,所以通讯时session会分布在多台服务器。比如用户A的session在机器1,用户B的session在机器2,此时A发送给B,就无法单独通过机器1完成。
因为机器1拿不到机器2里的session,所以消息发不过去。此时只能借助别的中间件来实现,比如借助消息中间件kafka实现。
机器1将消息发送给kafka,然后机器1和机器2都监听kafka,然后查看用户对应的session是否在本机,如果在本机则发送出去。
2.5、消息推送模块
模块3提到的消息发送流程中,消息发送给 消息中间件,然后服务器消费到消费,再通过本机的session推送给客户端。
三、遇到的几个问题
3.1、连接自动断开
WebSocket连接之后,发现一个问题:每隔一段时间如果不传送数据的话,与前端的连接就会自动断开。可以采用心跳消息的方式来解决这个问题。比如客服端每隔30秒自动发送ping消息给服务端,服务端返回pong。
3.2、Session无法被序列化
分布式场景会存在这样的问题:当一次请求负载到第一台服务器时,session在第一台服务器线程上,第二次请求,负载到第二台服务器上,此时通过userId查找当前用户的session时,是查找不到的。
本来想着把session存入到redis中,就可以从redis获取用户的session,希望用这种方式来解决分布式场景下消息发送的问题。但是会出现如下错误:
The remote endpoint was in state [STREAM_WRITING] which is an invalid state for called method
翻看了session源码,发现session无法被序列化。所以这个方案只能放弃。解决方案请看下面的问题5或者上面的架构图。
3.3、对象无法自动注入
使用了@ServerEndpoint注解的类中使用@Resource或@Autowired注入对象都会失败,并且报空指针异常。
原因是WebSocket服务是线程安全的,那么当我们去发起一个ws连接时,就会创建一个端点对象。WebSocket服务是多对象的,不是单例的。而我们的Spring的Bean默认就是单例的,在非单例类中注入一个单例的Bean是冲突的。
或者说:
Spring管理采用单例模式(singleton),而 WebSocket 是多对象的,即每个客户端对应后台的一个 WebSocket 对象,也可以理解成 new 了一个 WebSocket,这样当然是不能获得自动注入的对象了,因为这两者刚好冲突。
@Autowired 注解注入对象操作是在启动时执行的,而不是在使用时,而 WebSocket 是只有连接使用时才实例化对象,且有多个连接就有多个对象。所以我们可以得出结论,这个 Service 根本就没有注入到 WebSocket 当中。
如何解决呢?
使用静态对象,并且对外暴露set方法,这样在对象初始化的时候,将其注入到WebSocketServer中。比如说这样:
@ServerEndpoint("/websocket/{userId}")
@Component
@Slf4j
public class WebSocketServer {
private static MessageStore messageStore;
private static MessageSender messageSender;
public static void setMessageStore(MessageStore messageStore) {
WebSocketServer.messageStore = messageStore;
}
public static void setMessageSender(MessageSender messageSender) {
WebSocketServer.messageSender = messageSender;
}
}
@Slf4j
@Service
public class MessageStore {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@PostConstruct
public void init() {
WebSocketServer.setMessageStore(this);
}
}
3.4、分布式场景消息如何发给客户端
问题2中提到了分布式场景下存在的session不在本机的问题,这种场景可以通过发送消息中间件的方式解决。具体这样解决:
每次连接时,都将userId和对应的session存入到本机,发送消息时,直接发送给MQ-Broker,然后每台应用负载都去消费这个消息,拿到消息之后,判断在本机能根据userId是否能找到session,找到session则推送到客户端。
3.5、部署时Nginx配置问题
代码开发完毕之后,本机跑通后,然后部署到服务器之后,还差很重要的一步:配置nginx代理。
3.5.1、给后端应用部署独立域名
要给后端应用部署独立域名,nginx代理直接转发到应用的独立域名,不要走微服务的gateway网关转发过去。
3.5.2、多层nginx转发问题
当只有一层nginx的时候,配置比较简单,如下:
location ~* ^/api/websocket/* {
proxy_pass http://mangodwsstest.mangod.top;
proxy_read_timeout 300s;
proxy_send_timeout 300s;
proxy_set_header Host mangodwsstest.mangod.top;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header X-Real-IP $remote_addr;
}
但是,当有两层nginx转发的时候,问题就出现了。
在最外层的nginx需要使用如下配置,不能照抄后面一层的配置。proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for和proxy_set_header X-Forwarded-Proto $scheme这两个配置不能少,用来将协议和真实IP传递给后面一层的nginx。
location ~* ^/api/websocket/* {
proxy_pass http://mangodwsstest.mangod.top;
proxy_read_timeout 300s;
proxy_send_timeout 300s;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
}
四、完整代码和示例
4.1、页面效果如下
开启两个web页面,用户1输入用户2的用户ID,输入发送消息内容,点击发送。在用户2的页面的接受消息内容可以看到发送的消息。
4.2、代码结构
4.3、代码地址
https://github.com/yclxiao/spring-websocket.git
五、总结
本文聊了Springboot如何集成Websocket、IM及时通讯需要哪些模块、开发和部署过程中遇到的问题、以及实现小型IM及时通讯的代码。希望对你有帮助!
- 上一篇:SpringBoot扩展——应用Web Socket!
- 已经是最后一篇了
相关推荐
- Springboot 整合 Websocket 轻松实现IM及时通讯
-
一、方案实践集成分为三步:添加依赖、增加配置类和消息核心类、前端集成。1.1、添加依赖<dependency><groupId>org.springframework...
- SpringBoot扩展——应用Web Socket!
-
应用WebSocket目前,网络上的即时通信App有很多,如QQ、微信和飞书等,按照以往的技术来说,即时功能通常会采用服务器轮询和Comet技术来解决。HTTP是非持久化、单向的网络协议,在建立连接...
- 【Spring Boot】WebSocket 的 6 种集成方式
-
介绍由于前段时间我实现了一个库【SpringCloud】一个配置注解实现WebSocket集群方案以至于我对WebSocket的各种集成方式做了一些研究目前我所了解到的就是下面这些了(就一个破w...
- SpringBoot生产级WebSocket集群实践,支持10万连接!
-
1、问题背景智慧门诊系统旨在从一定程度上解决患者面临的三长一短(挂号、看病、取药时间长,医生问诊时间短)的问题。实现“诊前、诊中、诊后”实时智能一体化,整合完善医院工作流程。围绕门诊看病的各个环节,让...
- Spring Boot3 中 WebSocket 实现数据实时通信全解析
-
各位互联网大厂的开发同仁们,在如今的互联网应用开发中,实时通信功能越来越重要。比如在线聊天、数据推送、实时通知等场景,都离不开高效的实时通信技术。而WebSocket作为一种高效的双向通信协议,在...
- Java WebSocket 示例(java nio websocket)
-
一、环境准备1.依赖配置(Maven)在pom.xml中添加WebSocket依赖:xml<!--SpringBootWebSocket--><dependen...
- Spring Boot整合WebSocket:开启实时通信之旅
-
SpringBoot整合WebSocket:开启实时通信之旅今天咱们来聊聊SpringBoot整合WebSocket这件大事儿。说到实时通信,你是不是第一时间想到QQ、微信这些聊天工具?没错,We...
- Spring Boot3 竟能如此轻松整合 WebSocket 技术,你还不知道?
-
在当今互联网大厂的软件开发领域,实时通信的需求愈发迫切。无论是在线聊天应用、实时数据更新,还是协同办公系统,都离不开高效的实时通信技术支持。而WebSocket作为一种能够实现浏览器与服务器之间持...
- Spring Boot集成WebSocket(springboot集成websocket)
-
一、基础配置依赖引入<dependency><groupId>org.springframework.boot</groupId><artifactId>...
- Springboot下的WebSocket开发(springboot websocket server)
-
今天遇到一个需求,需要对接第三方扫码跳转。一种方案是前端页面轮询后端服务,但是这种空轮询会虚耗资源,实时性比较差而且也不优雅。所以决定使用另一种方案,websocket。以前就知道websocket,...
- springboot websocket开发(java spring boot websocket)
-
maven依赖SpringBoot2.0对WebSocket的支持简直太棒了,直接就有包可以引入<dependency><groupId>org....
- Python界面(GUI)编程PyQt5窗体小部件
-
一、简介在Qt(和大多数用户界面)中,“小部件”是用户可以与之交互的UI组件的名称。用户界面由布置在窗口内的多个小部件组成。Qt带有大量可用的小部件,也允许您创建自己的自定义和自定义小部件。二、小部件...
- 实战PyQt5: 014-下拉列表框控件QComboBox
-
QComboBox简介QComboBox下拉列表框,是一个集按钮和下拉列表选项于一体的部件。QComboBox提供了一种向用户呈现选项列表的方式,其占用最小量的屏幕空间。QComboBox中的常用方法...
- Python小白逆袭!7天吃透PyQt6,独立开发超酷桌面应用
-
PythonGUI编程:PyQt6从入门到实战的全面指南在Python的庞大生态系统中,PyQt6作为一款强大的GUI(GraphicalUserInterface,图形用户界面)编程框架,为开...
- 如何用 PyQt6 打造一个功能完善的 SQLite 数据库管理工具
-
如何使用PyQt6和qt_material库,打造一个功能完善的SQLite数据库管理工具,轻松管理和查询SQLite数据库。一、目标数据库连接与表管理:支持连接SQLite数据库...
- 一周热门
-
-
Python实现人事自动打卡,再也不会被批评
-
【验证码逆向专栏】vaptcha 手势验证码逆向分析
-
Psutil + Flask + Pyecharts + Bootstrap 开发动态可视化系统监控
-
一个解决支持HTML/CSS/JS网页转PDF(高质量)的终极解决方案
-
再见Swagger UI 国人开源了一款超好用的 API 文档生成框架,真香
-
网页转成pdf文件的经验分享 网页转成pdf文件的经验分享怎么弄
-
C++ std::vector 简介
-
系统C盘清理:微信PC端文件清理,扩大C盘可用空间步骤
-
10款高性能NAS丨双十一必看,轻松搞定虚拟机、Docker、软路由
-
python使用fitz模块提取pdf中的图片
-
- 最近发表
-
- Springboot 整合 Websocket 轻松实现IM及时通讯
- SpringBoot扩展——应用Web Socket!
- 【Spring Boot】WebSocket 的 6 种集成方式
- SpringBoot生产级WebSocket集群实践,支持10万连接!
- Spring Boot3 中 WebSocket 实现数据实时通信全解析
- Java WebSocket 示例(java nio websocket)
- Spring Boot整合WebSocket:开启实时通信之旅
- Spring Boot3 竟能如此轻松整合 WebSocket 技术,你还不知道?
- Spring Boot集成WebSocket(springboot集成websocket)
- Springboot下的WebSocket开发(springboot websocket server)
- 标签列表
-
- python判断字典是否为空 (50)
- crontab每周一执行 (48)
- aes和des区别 (43)
- bash脚本和shell脚本的区别 (35)
- canvas库 (33)
- dataframe筛选满足条件的行 (35)
- gitlab日志 (33)
- lua xpcall (36)
- blob转json (33)
- python判断是否在列表中 (34)
- python html转pdf (36)
- 安装指定版本npm (37)
- idea搜索jar包内容 (33)
- css鼠标悬停出现隐藏的文字 (34)
- linux nacos启动命令 (33)
- gitlab 日志 (36)
- adb pull (37)
- table.render (33)
- python判断元素在不在列表里 (34)
- python 字典删除元素 (34)
- vscode切换git分支 (35)
- python bytes转16进制 (35)
- grep前后几行 (34)
- hashmap转list (35)
- c++ 字符串查找 (35)