SpringBoot+webSocket+Vue设置后台向前端推送消息

浅浅的花香味﹌ 2021-07-09 03:55 682阅读 0赞

应用场景介绍:

在页面的数据需要实时刷新的时候,或者在页面需要接收后台的消息时候,如果采用前端轮询会造成资源占用较大,并且数据刷新也是不及时的,比如当我后台在监听MQ的消息时候,当从MQ监听到消息后我需要将MQ消息推送到前端实时展示,这时候就需要用到webSocket了。

1.首先搭建一个SpringBoot的项目,这里我就不重复了,然后引入jar包

  1. <!-- WebSocket -->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-websocket</artifactId>
  5. <version>2.1.0.RELEASE</version>
  6. </dependency>

2、编写websocketConfig配置类

  1. import org.springframework.context.annotation.Bean;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.web.socket.server.standard.ServerEndpointExporter;
  4. /**
  5. * @Author dingchengxiang
  6. * @Description //TODO WebSocket配置类
  7. * @Date 15:53 2019/11/11
  8. * @Param
  9. * @return
  10. **/
  11. @Configuration
  12. public class WebSocketConfig {
  13. @Bean
  14. public ServerEndpointExporter serverEndpointExporter(){
  15. return new ServerEndpointExporter();
  16. }
  17. }

3.websocket的实现类

  1. import lombok.extern.slf4j.Slf4j;
  2. import org.springframework.stereotype.Component;
  3. import javax.websocket.*;
  4. import javax.websocket.server.PathParam;
  5. import javax.websocket.server.ServerEndpoint;
  6. import java.io.IOException;
  7. import java.util.concurrent.CopyOnWriteArraySet;
  8. @Component
  9. @ServerEndpoint("/push/websocket")
  10. @Slf4j
  11. public class WebSocketServer {
  12. //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
  13. private static int onlineCount = 0;
  14. //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
  15. private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
  16. //与某个客户端的连接会话,需要通过它来给客户端发送数据
  17. private Session session;
  18. //接收sid
  19. private String sid="";
  20. /**
  21. * 连接建立成功调用的方法*/
  22. @OnOpen
  23. public void onOpen(Session session,@PathParam("sid") String sid) {
  24. this.session = session;
  25. webSocketSet.add(this); //加入set中
  26. addOnlineCount(); //在线数加1
  27. log.info("有新窗口开始监听:"+sid+",当前在线人数为" + getOnlineCount());
  28. this.sid=sid;
  29. /*try {
  30. sendMessage(JSON.toJSONString(RestResponse.success()));
  31. } catch (IOException e) {
  32. log.error("websocket IO异常");
  33. }*/
  34. }
  35. /**
  36. * 连接关闭调用的方法
  37. */
  38. @OnClose
  39. public void onClose() {
  40. webSocketSet.remove(this); //从set中删除
  41. subOnlineCount(); //在线数减1
  42. log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
  43. }
  44. /**
  45. * 收到客户端消息后调用的方法
  46. *
  47. * @param message 客户端发送过来的消息*/
  48. @OnMessage
  49. public void onMessage(String message, Session session) {
  50. //log.info("收到来自窗口"+sid+"的信息:"+message);
  51. if("heart".equals(message)){
  52. try {
  53. sendMessage("heartOk");
  54. } catch (IOException e) {
  55. e.printStackTrace();
  56. }
  57. }
  58. }
  59. /**
  60. *
  61. * @param session
  62. * @param error
  63. */
  64. @OnError
  65. public void onError(Session session, Throwable error) {
  66. log.error("发生错误");
  67. error.printStackTrace();
  68. }
  69. /**
  70. * 实现服务器主动推送
  71. */
  72. public void sendMessage(String message) throws IOException {
  73. this.session.getBasicRemote().sendText(message);
  74. }
  75. /**
  76. * 群发自定义消息
  77. * */
  78. public static void sendInfo(String message) throws IOException {
  79. for (WebSocketServer item : webSocketSet) {
  80. try {
  81. //这里可以设定只推送给这个sid的,为null则全部推送
  82. // if(sid==null) {
  83. item.sendMessage(message);
  84. log.info("推送消息到窗口"+item.sid+",推送内容:"+message);
  85. // }else if(item.sid.equals(sid)){
  86. // item.sendMessage(message);
  87. // }
  88. } catch (IOException e) {
  89. continue;
  90. }
  91. }
  92. }
  93. public static synchronized int getOnlineCount() {
  94. return onlineCount;
  95. }
  96. public static synchronized void addOnlineCount() {
  97. WebSocketServer.onlineCount++;
  98. }
  99. public static synchronized void subOnlineCount() {
  100. WebSocketServer.onlineCount--;
  101. }
  102. }

4、新增一个控制层接口作为测试接口能够调用的

  1. /**
  2. * @Author dingchengxiang
  3. * @Description //TODO 测试websocket发送消息
  4. * @Date 14:41 2019/11/12
  5. * @Param []
  6. * @return java.lang.String
  7. **/
  8. @PostMapping("/sendAllWebSocket")
  9. public String test() {
  10. String text="你们好!这是websocket群体发送!";
  11. try {
  12. webSocketServer.sendInfo(text);
  13. }catch (IOException e){
  14. e.printStackTrace();
  15. }
  16. return text;
  17. }

此处需要注意一下,后台可能与拦截需要将接口放开,本人是在shiroConfig中进行设置

20191112144726920.png

5、编写前端vue的代码

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM0MTc4OTk4_size_16_color_FFFFFF_t_70

先在这两处添加,

  1. mounted () {
  2. // WebSocket
  3. if ('WebSocket' in window) {
  4. this.websocket = new WebSocket('ws://localhost:8080/自己的项目地址/push/websocket')
  5. // alert('连接浏览器')
  6. this.initWebSocket()
  7. } else {
  8. alert('当前浏览器 不支持')
  9. }
  10. },
  11. beforeDestroy () {
  12. this.onbeforeunload()
  13. },

然后在方法中编写具体实现

  1. methods: {
  2. initWebSocket () {
  3. // 连接错误
  4. this.websocket.onerror = this.setErrorMessage
  5. // 连接成功
  6. this.websocket.onopen = this.setOnopenMessage
  7. // 收到消息的回调
  8. this.websocket.onmessage = this.setOnmessageMessage
  9. // 连接关闭的回调
  10. this.websocket.onclose = this.setOncloseMessage
  11. // 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
  12. window.onbeforeunload = this.onbeforeunload
  13. },
  14. setErrorMessage () {
  15. console.log('WebSocket连接发生错误 状态码:' + this.websocket.readyState)
  16. },
  17. setOnopenMessage () {
  18. console.log('WebSocket连接成功 状态码:' + this.websocket.readyState)
  19. },
  20. setOnmessageMessage (event) {
  21. // 根据服务器推送的消息做自己的业务处理
  22. console.log('服务端返回:' + event.data)
  23. },
  24. setOncloseMessage () {
  25. console.log('WebSocket连接关闭 状态码:' + this.websocket.readyState)
  26. },
  27. onbeforeunload () {
  28. this.closeWebSocket()
  29. },
  30. closeWebSocket () {
  31. this.websocket.close()
  32. }
  33. }

这个时候启动我们就可以看到效果了,页面控制台打印的值

20191112145104206.png

后台控制台打印的值

20191112145157301.png

到这一步基本的就已经实现了,但是我们现在要加入中间件MQ监听到消息后进行消息返回,那么还需要下面几步,

6、MQ我在这个demo中没有集成,我就用一个定时任务来模拟MQ监听到消息以后的处理步骤。

新建一个Task类

  1. /**
  2. * @Author dingchengxiang
  3. * @Description //TODO 消息定时器,通知websocket
  4. * @Date 14:56 2019/11/12
  5. * @Param
  6. * @return
  7. **/
  8. @Component
  9. public class Task {
  10. @Autowired
  11. private WebSocketServer webSocketServer;
  12. /**
  13. * @throws Exception
  14. */
  15. @Scheduled(cron="0/5 * * * * ? ")
  16. public void JqcaseSearch() {
  17. try {
  18. System.out.println("这是心跳");
  19. webSocketServer.sendInfo("主动推送消息");
  20. } catch (Exception e) {
  21. e.printStackTrace();
  22. }
  23. }
  24. }

这么设置,每隔五秒,就会模拟MQ监听到一条消息,然后调用WebSocket服务的发送消息,此时我们需要在启动类上面加一个定时器注解

  1. @SpringBootApplication
  2. @EnableScheduling
  3. public class Application {
  4. public static void main(String[] args) {
  5. SpringApplication.run(RenrenApplication.class, args);
  6. }
  7. }

加上@EnableScheduling注解后定时器才会有效果

这时候我们再编写个简单的html页面来帮助我们观察

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width,initial-scale=1.0">
  7. <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
  8. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
  9. integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  10. <title>websocket测试页面</title>
  11. </head>
  12. <body>
  13. <div class="panel panel-default">
  14. <div class="panel-body">
  15. <div class="row">
  16. <div class="col-md-6">
  17. <div class="input-group">
  18. <span class="input-group-addon">ws地址</span>
  19. <input type="text" id="address" class="form-control" placeholder="ws地址"
  20. aria-describedby="basic-addon1" value="ws://localhost:8080/自己的项目/push/websocket">
  21. <div class="input-group-btn">
  22. <button class="btn btn-default" type="submit" id="connect">连接</button>
  23. </div>
  24. </div>
  25. </div>
  26. </div>
  27. <div class="row" style="margin-top: 10px;display: none;" id="msg-panel">
  28. <div class="col-md-6">
  29. <div class="input-group">
  30. <span class="input-group-addon">消息</span>
  31. <input type="text" id="msg" class="form-control" placeholder="消息内容" aria-describedby="basic-addon1">
  32. <div class="input-group-btn">
  33. <button class="btn btn-default" type="submit" id="send">发送</button>
  34. </div>
  35. </div>
  36. </div>
  37. </div>
  38. <div class="row" style="margin-top: 10px; padding: 10px;">
  39. <div class="panel panel-default">
  40. <div class="panel-body" id="log" style="height: 450px;overflow-y: auto;">
  41. </div>
  42. </div>
  43. </div>
  44. </div>
  45. </div>
  46. <script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
  47. <script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"
  48. integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
  49. crossorigin="anonymous"></script>
  50. <script type="text/javascript">
  51. $(function () {
  52. var _socket;
  53. $("#connect").click(function () {
  54. _socket = new _websocket($("#address").val());
  55. _socket.init();
  56. });
  57. $("#send").click(function () {
  58. var _msg = $("#msg").val();
  59. output("发送消息:" + _msg);
  60. _socket.client.send(_msg);
  61. });
  62. });
  63. function output(e) {
  64. var _text = $("#log").html();
  65. $("#log").html(_text + "<br>" + e);
  66. }
  67. function _websocket(address) {
  68. this.address = address;
  69. this.client;
  70. this.init = function () {
  71. if (!window.WebSocket) {
  72. this.websocket = null;
  73. return;
  74. }
  75. var _this = this;
  76. var _client = new window.WebSocket(_this.address);
  77. _client.onopen = function () {
  78. output("websocket打开");
  79. $("#msg-panel").show();
  80. };
  81. _client.onclose = function () {
  82. _this.client = null;
  83. output("websocket关闭");
  84. $("#msg-panel").hide();
  85. };
  86. _client.onmessage = function (evt) {
  87. output(evt.data);
  88. };
  89. _this.client = _client;
  90. };
  91. return this;
  92. }
  93. </script>
  94. </body>
  95. </html>

这时候启动SpringBoot,再运行html,

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM0MTc4OTk4_size_16_color_FFFFFF_t_70 1

此时连接后我们会发现,后台会一直向页面推送消息

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM0MTc4OTk4_size_16_color_FFFFFF_t_70 2

同时在VUE的控制台也会发现

20191112150420303.png

有消息产生,到此demo就结束了,我们可以利用返回的消息做数据刷新,做消息推送等。

2019年11月13日补充:

需要对列表进行推送刷新的话,有两种将数据推送的方式

1、修改发送的消息为Object类型

  1. /**
  2. * 实现服务器主动推送
  3. */
  4. public void sendMessage(Object message) throws Exception {
  5. this.session.getBasicRemote().sendObject(message);
  6. }

但是修改之后发现会报错

20191113170113883.png

提示我没有编码类。

之后查阅一下,发现需要编码类,比较麻烦,就没有才用了

2、采用json字符串的方式发送到前端,FastJsonUtils是我自己编写的json工具类

  1. public void JqcaseSearch() {
  2. Map<String, Object> params = new HashMap<>();
  3. params.put("t","1573630630476");
  4. params.put("page","1");
  5. params.put("limit","10");
  6. PageUtils page = sysRoleService.queryPage(params);
  7. JSONObject jsonObject = FastJsonUtils.toJsonObject(R.ok().put("page", page));
  8. try {
  9. webSocketServer.sendData(jsonObject);
  10. } catch (Exception e) {
  11. e.printStackTrace();
  12. }
  13. }

再编写调用类

  1. /**
  2. * 自定义刷新数据
  3. * */
  4. public static void sendData(JSONObject object) throws Exception {
  5. for (WebSocketServer item : webSocketSet) {
  6. try {
  7. item.sendMessage(object.toJSONString());
  8. log.info("推送消息到窗口,推送内容:"+object);
  9. } catch (IOException e) {
  10. continue;
  11. }
  12. }

再调用主动推送的方法

  1. /**
  2. * 实现服务器主动推送
  3. */
  4. public void sendMessage(String message) throws Exception {
  5. /* this.session.getBasicRemote().sendObject(message);*/
  6. this.session.getBasicRemote().sendText(message);
  7. }

最后到页面将字符串转化为jsondata

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM0MTc4OTk4_size_16_color_FFFFFF_t_70 3

最后再根据自己的实际页面将jsondata里的数据放到到页面上去

20191113170813118.png

发表评论

表情:
评论列表 (有 0 条评论,682人围观)

还没有评论,来说两句吧...

相关阅读