SpringBoot2.0集成WebSocket,实现后台向前端推送信息
SpringBoot+WebSocket集成
- 什么是WebSocket?
- 为什么需要 WebSocket?
- 前言
- maven依赖
- WebSocketConfig
- WebSocketServer
- 消息推送
- 页面发起
- 运行效果
- 后续
- Websocker注入Bean问题
- netty-websocket-spring-boot-starter
- Springboot2+Netty+Websocket
- ServerEndpointExporter错误
- 正式项目的前端WebSocket框架 GoEasy
- `@Component`和`@ServerEndpoint`关于是否单例模式,能否使用static Map等一些问题的解答
- Vue版本的websocket连接
什么是WebSocket?
WebSocket协议是基于TCP的一种新的网络协议。它实现了浏览器与服务器全双工(full-duplex)通信——允许服务器主动发送信息给客户端。
为什么需要 WebSocket?
初次接触 WebSocket 的人,都会问同样的问题:我们已经有了 HTTP 协议,为什么还需要另一个协议?它能带来什么好处?
- 答案很简单,因为 HTTP 协议有一个缺陷:通信只能由客户端发起,HTTP 协议做不到服务器主动向客户端推送信息。
举例来说,我们想要查询当前的排队情况,只能是页面轮询向服务器发出请求,服务器返回查询结果。轮询的效率低,非常浪费资源(因为必须不停连接,或者 HTTP 连接始终打开)。因此WebSocket 就是这样发明的。
前言
2020-10-20
教程补充:
- 补充关于
@Component
和@ServerEndpoint
关于是否单例模式等的解答,感谢大家热心提问和研究。 Vue
版本的websocket连接方法
2020-01-05
教程补充:
- 整合了
IM相关的优化
- 优化
开启/关闭连接的处理
- 上传到
开源项目
spring-cloud-study-websocket,方便大家下载代码。
感谢
大家的支持和留言,14W访问量是满满的动力!接下来还会有websocket+redis集群优化篇
针对多ws服务器做简单优化处理,敬请期待!
话不多说,马上进入干货时刻。
maven依赖
SpringBoot2.0对WebSocket的支持简直太棒了,直接就有包可以引入
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
WebSocketConfig
启用WebSocket的支持也是很简单,几句代码搞定
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;/*** 开启WebSocket支持* @author zhengkai.blog.csdn.net*/
@Configuration
public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } }
WebSocketServer
这就是重点了,核心都在这里。
因为WebSocket是类似客户端服务端的形式(采用ws协议),那么这里的WebSocketServer其实就相当于一个ws协议的Controller
直接
@ServerEndpoint("/imserver/{userId}")
、@Component
启用即可,然后在里面实现@OnOpen
开启连接,@onClose
关闭连接,@onMessage
接收消息等方法。新建一个
ConcurrentHashMap
webSocketMap 用于接收当前userId的WebSocket,方便IM之间对userId进行推送消息。单机版
实现到这里就可以。集群版
(多个ws节点)还需要借助mysql或者redis等进行处理,改造对应的sendMessage
方法即可。
package com.softdev.system.demo.config;import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;/*** @author zhengkai.blog.csdn.net*/
@ServerEndpoint("/imserver/{userId}")
@Component
public class WebSocketServer {static Log log=LogFactory.get(WebSocketServer.class);/**静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。*/private static int onlineCount = 0;/**concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。*/private static ConcurrentHashMap<String,WebSocketServer> webSocketMap = new ConcurrentHashMap<>();/**与某个客户端的连接会话,需要通过它来给客户端发送数据*/private Session session;/**接收userId*/private String userId="";/*** 连接建立成功调用的方法*/@OnOpenpublic void onOpen(Session session,@PathParam("userId") String userId) {this.session = session;this.userId=userId;if(webSocketMap.containsKey(userId)){webSocketMap.remove(userId);webSocketMap.put(userId,this);//加入set中}else{webSocketMap.put(userId,this);//加入set中addOnlineCount();//在线数加1}log.info("用户连接:"+userId+",当前在线人数为:" + getOnlineCount());try {sendMessage("连接成功");} catch (IOException e) {log.error("用户:"+userId+",网络异常!!!!!!");}}/*** 连接关闭调用的方法*/@OnClosepublic void onClose() {if(webSocketMap.containsKey(userId)){webSocketMap.remove(userId);//从set中删除subOnlineCount();}log.info("用户退出:"+userId+",当前在线人数为:" + getOnlineCount());}/*** 收到客户端消息后调用的方法** @param message 客户端发送过来的消息*/@OnMessagepublic void onMessage(String message, Session session) {log.info("用户消息:"+userId+",报文:"+message);//可以群发消息//消息保存到数据库、redisif(StringUtils.isNotBlank(message)){try {//解析发送的报文JSONObject jsonObject = JSON.parseObject(message);//追加发送人(防止串改)jsonObject.put("fromUserId",this.userId);String toUserId=jsonObject.getString("toUserId");//传送给对应toUserId用户的websocketif(StringUtils.isNotBlank(toUserId)&&webSocketMap.containsKey(toUserId)){webSocketMap.get(toUserId).sendMessage(jsonObject.toJSONString());}else{log.error("请求的userId:"+toUserId+"不在该服务器上");//否则不在这个服务器上,发送到mysql或者redis}}catch (Exception e){e.printStackTrace();}}}/**** @param session* @param error*/@OnErrorpublic void onError(Session session, Throwable error) {log.error("用户错误:"+this.userId+",原因:"+error.getMessage());error.printStackTrace();}/*** 实现服务器主动推送*/public void sendMessage(String message) throws IOException {this.session.getBasicRemote().sendText(message);}/*** 发送自定义消息* */public static void sendInfo(String message,@PathParam("userId") String userId) throws IOException {log.info("发送消息到:"+userId+",报文:"+message);if(StringUtils.isNotBlank(userId)&&webSocketMap.containsKey(userId)){webSocketMap.get(userId).sendMessage(message);}else{log.error("用户"+userId+",不在线!");}}public static synchronized int getOnlineCount() {return onlineCount;}public static synchronized void addOnlineCount() {WebSocketServer.onlineCount++;}public static synchronized void subOnlineCount() {WebSocketServer.onlineCount--;}
}
消息推送
至于推送新信息,可以再自己的Controller写个方法调用WebSocketServer.sendInfo();即可
import com.softdev.system.demo.config.WebSocketServer;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import java.io.IOException;/*** WebSocketController* @author zhengkai.blog.csdn.net*/
@RestController
public class DemoController {@GetMapping("index")public ResponseEntity<String> index(){return ResponseEntity.ok("请求成功");}@GetMapping("page")public ModelAndView page(){return new ModelAndView("websocket");}@RequestMapping("/push/{toUserId}")public ResponseEntity<String> pushToWeb(String message, @PathVariable String toUserId) throws IOException {WebSocketServer.sendInfo(message,toUserId);return ResponseEntity.ok("MSG SEND SUCCESS");}
}
页面发起
页面用js代码调用websocket
,当然,太古老的浏览器是不行的,一般新的浏览器或者谷歌浏览器是没问题的。还有一点,记得协议是ws
的,如果使用了一些路径类,可以replace(“http”,“ws”)来替换协议。
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>websocket通讯</title>
</head>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>var socket;function openSocket() {if(typeof(WebSocket) == "undefined") {console.log("您的浏览器不支持WebSocket");}else{console.log("您的浏览器支持WebSocket");//实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接//等同于socket = new WebSocket("ws://localhost:8888/xxxx/im/25");//var socketUrl="${request.contextPath}/im/"+$("#userId").val();var socketUrl="http://localhost:9999/demo/imserver/"+$("#userId").val();socketUrl=socketUrl.replace("https","ws").replace("http","ws");console.log(socketUrl);if(socket!=null){socket.close();socket=null;}socket = new WebSocket(socketUrl);//打开事件socket.onopen = function() {console.log("websocket已打开");//socket.send("这是来自客户端的消息" + location.href + new Date());};//获得消息事件socket.onmessage = function(msg) {console.log(msg.data);//发现消息进入 开始处理前端触发逻辑};//关闭事件socket.onclose = function() {console.log("websocket已关闭");};//发生了错误事件socket.onerror = function() {console.log("websocket发生了错误");}}}function sendMessage() {if(typeof(WebSocket) == "undefined") {console.log("您的浏览器不支持WebSocket");}else {console.log("您的浏览器支持WebSocket");console.log('{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}');socket.send('{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}');}}
</script>
<body>
<p>【userId】:<div><input id="userId" name="userId" type="text" value="10"></div>
<p>【toUserId】:<div><input id="toUserId" name="toUserId" type="text" value="20"></div>
<p>【toUserId】:<div><input id="contentText" name="contentText" type="text" value="hello websocket"></div>
<p>【操作】:<div><a onclick="openSocket()">开启socket</a></div>
<p>【操作】:<div><a onclick="sendMessage()">发送消息</a></div>
</body></html>
运行效果
- v20200105,加入开源项目spring-cloud-study-websocket,更新运行效果,更方便理解。
- v1.1的效果,刚刚修复了日志,并且支持指定监听某个端口,代码已经全部更新,现在是这样的效果
- 打开两个页面,按F12调出控控制台查看测试效果:
页面 | 参数 |
---|---|
http://localhost:9999/demo/page | fromUserId=10,toUserId=20 |
http://localhost:9999/demo/page | fromUserId=20,toUserId=10 |
分别开启socket
,再发送消息
2. 向前端推送数据:
- http://localhost:9999/demo/push/10?message=123123
通过调用push api
,可以向指定的userId推送信息
,当然报文这里乱写,建议规定好格式。
后续
针对简单IM的业务场景,进行了一些优化,可以看后续的文章SpringBoot2+WebSocket之聊天应用实战(优化版本)(v20201005已整合
)
主要变动是CopyOnWriteArraySet改为ConcurrentHashMap
,保证多线程安全同时方便利用map.get(userId)
进行推送到指定端口。
相比之前的Set,Set遍历是费事且麻烦的事情,而Map的get是简单便捷的,当WebSocket数量大的时候,这个小小的消耗就会聚少成多,影响体验,所以需要优化。在IM的场景下,指定userId进行推送消息更加方便。
Websocker注入Bean问题
关于这个问题,可以看最新发表的这篇文章,在参考和研究了网上一些攻略后,项目已经通过该方法注入成功,大家可以参考。
关于controller调用controller/service调用service/util调用service/websocket中autowired的解决方法
netty-websocket-spring-boot-starter
Springboot2构建基于Netty的高性能Websocket服务器(netty-websocket-spring-boot-starter)
只需要换个starter即可实现高性能websocket,赶紧使用吧
Springboot2+Netty+Websocket
Springboot2+Netty实现Websocket,使用官方的netty-all的包,比原生的websocket更加稳定更加高性能,同等配置情况下可以handle更多的连接。
代码样式全部已经更正,也支持websocket连接url带参数功能,另外也感谢大家的阅读和评论,一起进步,谢谢!~~
ServerEndpointExporter错误
org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘
serverEndpointExporter
’ defined in class path resource [com/xxx/WebSocketConfig.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: javax.websocket.server.ServerContainer not available
感谢@来了老弟儿 的反馈:
如果tomcat部署一直报这个错,请移除 WebSocketConfig
中@Bean ServerEndpointExporter
的注入 。
ServerEndpointExporter
是由Spring官方提供的标准实现,用于扫描ServerEndpointConfig
配置类和@ServerEndpoint
注解实例。使用规则也很简单:
- 如果使用默认的嵌入式容器 比如
Tomcat
则必须手工在上下文提供ServerEndpointExporter
。 - 如果使用
外部容器部署war
包,则不需要
提供提供ServerEndpointExporter
,因为此时SpringBoot默认将扫描服务端的行为交给外部容器处理,所以线上部署的时候要把WebSocketConfig中这段注入bean的代码注掉。
正式项目的前端WebSocket框架 GoEasy
感谢kkatrina
的补充,正式的项目中,一般是用第三方websocket框架来做,稳定性、实时性有保证的多,也会包括一些心跳、重连机制。
GoEasy专注于服务器与浏览器,浏览器与浏览器之间消息推送,完美兼容世界上的绝大多数浏览器,包括IE6, IE7之类的非常古老的浏览器。支持Uniapp,各种小程序,react,vue等所有主流Web前端技术。
GoEasy采用 发布/订阅 的消息模式,帮助您非常轻松的实现一对一,一对多的通信。
https://www.goeasy.io/cn/doc/
@Component
和@ServerEndpoint
关于是否单例模式,能否使用static Map等一些问题的解答
看到大家都在热心的讨论关于是否单例模式这个问题,请大家相信自己的直接,如果websocket是单例模式,还怎么服务这么多session呢。
- websocket是
原型模式
,@ServerEndpoint
每次建立双向通信的时候都会创建一个实例,区别于spring的单例模式。 - Spring的
@Component
默认是单例模式
,请注意,默认
而已,是可以被改变的。 - 这里的
@Component
仅仅为了支持@Autowired依赖注入
使用,如果不加则不能注入任何东西,为了方便。 - 什么是
prototype 原型模式
? 基本就是你需要从A的实例得到一份与A内容相同,但是又互不干扰的实例B的话,就需要使用原型模式。 - 关于在原型模式下使用static 的
webSocketMap
,请注意这是ConcurrentHashMap ,也就是线程安全/线程同步的,而且已经是静态变量
作为全局调用,这种情况下是ok的,或者大家如果有顾虑或者更好的想法的化,可以进行改进。 例如使用一个中间类来接收和存放session。 - 为什么每次都@OnOpen都要检查
webSocketMap.containsKey(userId)
,首先了为了代码强壮性
考虑,假设代码以及机制没有问题,那么肯定这个逻辑是废的对吧。但是实际使用的时候发现偶尔会出现重连失败或者其他原因导致之前的session还存在,这里就做了一个清除旧session,迎接新session
的功能。
Vue版本的websocket连接
感谢**@GzrStudy**的贡献,供大家参考。
<script>
export default {data() {return {socket:null,userId:localStorage.getItem("ms_uuid"),toUserId:'2',content:'3'}},methods: {openSocket() {if (typeof WebSocket == "undefined") {console.log("您的浏览器不支持WebSocket");} else {console.log("您的浏览器支持WebSocket");//实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接//等同于socket = new WebSocket("ws://localhost:8888/xxxx/im/25");//var socketUrl="${request.contextPath}/im/"+$("#userId").val();var socketUrl ="http://localhost:8081/imserver/" + this.userId;socketUrl = socketUrl.replace("https", "ws").replace("http", "ws");console.log(socketUrl);if (this.socket != null) {this.socket.close();this.socket = null;}this.socket = new WebSocket(socketUrl);//打开事件this.socket = new WebSocket(socketUrl);//打开事件this.socket.onopen = function() {console.log("websocket已打开");//socket.send("这是来自客户端的消息" + location.href + new Date());};//获得消息事件this.socket.onmessage = function(msg) {console.log(msg.data);//发现消息进入 开始处理前端触发逻辑};//关闭事件this.socket.onclose = function() {console.log("websocket已关闭");};//发生了错误事件this.socket.onerror = function() {console.log("websocket发生了错误");};}},sendMessage() {if (typeof WebSocket == "undefined") {console.log("您的浏览器不支持WebSocket");} else {console.log("您的浏览器支持WebSocket");console.log('{"toUserId":"' +this.toUserId +'","contentText":"' +this.content +'"}');this.socket.send('{"toUserId":"' +this.toUserId +'","contentText":"' +this.content +'"}');}
}
SpringBoot2.0集成WebSocket,实现后台向前端推送信息相关推荐
- SpringBoot 集成 WebSocket,实现后台向前端推送信息
作者 | 大树先生 来源 | https://blog.csdn.net/MacWx/article/details/111319558 前言 在一次项目开发中,使用到了Netty网络应用框架,以及M ...
- SpringBoot集成WebSocket,实现后台向前端推送信息
作者 | 大树先生 来源 | https://blog.csdn.net/MacWx/article/details/111319558 前言 在一次项目开发中,使用到了Netty网络应用框架,以及M ...
- SpringBoot 集成 webSocket,实现后台向客户端推送消息
图文等内容参考链接 SpringBoot2.0集成WebSocket,实现后台向前端推送信息_Moshow郑锴的博客-CSDN博客_springboot websocket WebSocket 简介 ...
- SpringBoot使用Socket向前端推送消息
个人资源与分享网站:http://xiaocaoshare.com/ 1.对webSocket理解 WebSocket协议是基于TCP的一种新的网络协议.它实现了浏览器与服务器全双工(full-dup ...
- SpringBoot+Vue整合WebSocket实现前后端消息推送
场景 WebSocket HTTP 协议是一种无状态的.无连接的.单向的应用层协议.它采用了请求/响应模型.通信请求只能由客户端发起,服务端对请求做出应答处理. 这种通信模型有一个弊端:HTTP 协议 ...
- Springboot2.0集成阿里云RocketMQ
介绍 RocketMQ是出自阿里巴巴的一款开源消息中间件,在设计上借鉴了Kafka,2017年成为Apache顶级项目,虽然目前社区无法和Kafka比肩,但其历经多次天猫双十一的考验,其性能和稳定是毋 ...
- springboot2.0集成哨兵模式Redisson
学习网站:https://my.oschina.net/u/3959468/blog/2251918 1.Redisson Redisson 是一个在 Redis 的基础上实现的 Java 驻内存数据 ...
- 后端 消息 转发_springCloud 后端使用webSocket向前端推送消息
1.webSocket webSocket长连接是一种在单个tcp连接上进行全双工通信的协议,允许双向数据推送.一般微服务提供的restful API只是对前端请求做出相应.使用webSocket可以 ...
- WebSocket + SpringBoot + VUE实现后端实时向前端推送消息
一.目的 众所周知,正常来说在前后端通信中,后端往往处于一个被动的状态,对前端的请求作出对应的响应.但有的时候我们会遇到需要后端前前端推送数据的需求,比如消息.邮件等的推送.这个时候,实现的一种方式是 ...
最新文章
- java Export Excel POI 转
- eltable刷新整个表格方法_多个子表内容合并到总表,不用每次复制粘贴,全自动刷新...
- [转载] Python高级变量(列表、元组、字典、字符串、公共方法)
- 复地邮箱服务器地址,打印服务器设置方法
- ReactiveCocoa的学习内容
- Hibernate jar问题
- workbench谐响应
- RGB与十六进制颜色进行互转
- TCP/UDP端口列表
- [openwrt] [WIFI] 修改默认的SSID和密码
- 计算机系统结构 2:局部性原理
- VerA 0.15 by PE_kill
- java解析xml文件练习——通过应用包名获取应用图标即其他信息(基于魅族应用商店)...
- 简单工厂和抽象工厂有什么区别?
- 【Win8系统:速度快 启动快 关机慢】
- 从数组中找出最大的两个数
- 考研概率论--87年真题--MATLAB暴力求解
- 时间序列预测——LSTM模型(附代码实现)
- Noah Mt4跟单系统制作第五篇 Mt4TradeApi挂单篇
- 雪碧图 sprite
热门文章
- datasheet下载网站整理(查IC芯片手册)
- Fiddler屏蔽某些url的抓取方法
- 计算文本长度,区分中英文字符,中文算两个长度,英文算一个长度
- (SVN笔记)https内网IP端口配置SVN服务端+内网SVN客户端联合使用
- DoA 估计:多重信号分类 MUSIC 算法(附 MATLAB 代码)
- 网孔型初级维修电工实训考核装置
- 自己写的mfl.mop,com外挂
- Ambari-2.7.4和HDP-3.1.4安装(附Ambari和HDP安装包)
- matlab 平均梯度,OpenCV 自学笔记33. 计算图像的均值、标准差和平均梯度
- 课程拼团超级拼团公众号小程序制作