依星源码资源网,依星资源网

 找回密码
 立即注册

QQ登录

只需一步,快速开始

【好消息,好消息,好消息】VIP会员可以发表文章赚积分啦 !
查看: 44|回复: 0

springboot整合websocket实现消息推送

[复制链接] 主动推送

1万

主题

1万

帖子

1万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
15537
发表于 前天 12:03 | 显示全部楼层 |阅读模式
springboot整合websocket实现消息推送
​最近想起之前项目里面的一个实现,是关于订阅推送的,当粉丝订阅了大V或者说作者发布的内容被评论和点赞之后,对应的用户会受到通知,当然,本身系统用户并不多,所以直接采用的是轮训的方式,由前端这边定时向后端发起接口请求,获取消息推送,无疑呢,此种方式也可以解决问题,但是大部分请求基本无用,白白浪费带宽和网络资源。
今天难得媳妇儿带孩子回娘家了,下班到家也无事,便想着整理下前后端通过websocket实现消息推送的方式。当然,前端这块,主要采用原始的js通过websocket的方式获取消息,在微信公众号和支付宝小程序开发中都有相应的onWebSocekt方式,有兴趣的同学可以自行学习。
废话不多说,开始啃代码。
1、pom.xml

  1.         
  2.             org.springframework.boot
  3.             spring-boot-starter-websocket
  4.         


  5.         
  6.         
  7.             org.springframework.boot
  8.             spring-boot-starter-thymeleaf
  9.         
复制代码
2、application.yml
  1. server:
  2.   port: 8080


  3. spring:
  4.   thymeleaf:
  5.     cache: false # 开发时关闭缓存,不然没法看到实时页面
  6.     mode: HTML # 用非严格的 HTML
  7.     encoding: UTF-8
  8.     servlet:
  9.       content-type: text/html
复制代码
3、WebSocketServer,实现前后端的长连接
  1. package com.cookie.server;

  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import org.springframework.stereotype.Component;

  5. import javax.annotation.PostConstruct;
  6. import javax.websocket.*;
  7. import javax.websocket.server.ServerEndpoint;
  8. import java.io.IOException;
  9. import java.util.concurrent.CopyOnWriteArraySet;
  10. import java.util.concurrent.atomic.AtomicInteger;

  11. /**
  12. * @Author : cxq
  13. * @Date : 2020/8/31 15:50
  14. */

  15. // 前端通过该连接与后端保持交互
  16. @ServerEndpoint(value = "/server")
  17. @Component
  18. public class WebSocketServer {

  19.     @PostConstruct
  20.     public void init() {
  21.         System.out.println("websocket 加载");
  22.     }
  23.     private static Logger log = LoggerFactory.getLogger(WebSocketServer.class);
  24.     private static final AtomicInteger OnlineCount = new AtomicInteger(0);
  25.     // concurrent包的线程安全Set,用来存放每个客户端对应的Session对象。
  26.     private static CopyOnWriteArraySet SessionSet = new CopyOnWriteArraySet();


  27.     /**
  28.      * 连接建立成功调用的方法
  29.      */
  30.     @OnOpen
  31.     public void onOpen(Session session) {
  32.         SessionSet.add(session);
  33.         int cnt = OnlineCount.incrementAndGet(); // 在线数加1
  34.         log.info("有连接加入,当前连接数为:{}", cnt);
  35.         SendMessage(session, "连接成功");
  36.     }

  37.     /**
  38.      * 连接关闭调用的方法
  39.      */
  40.     @OnClose
  41.     public void onClose(Session session) {
  42.         SessionSet.remove(session);
  43.         int cnt = OnlineCount.decrementAndGet();
  44.         log.info("有连接关闭,当前连接数为:{}", cnt);
  45.     }

  46.     /**
  47.      * 收到客户端消息后调用的方法
  48.      *
  49.      * @param message
  50.      *            客户端发送过来的消息
  51.      */
  52.     @OnMessage
  53.     public void onMessage(String message, Session session) {
  54.         log.info("来自客户端的消息:{}",message);
  55.         SendMessage(session, "收到消息,消息内容:"+message);

  56.     }

  57.     /**
  58.      * 出现错误
  59.      * @param session
  60.      * @param error
  61.      */
  62.     @OnError
  63.     public void onError(Session session, Throwable error) {
  64.         log.error("发生错误:{},Session ID: {}",error.getMessage(),session.getId());
  65.         error.printStackTrace();
  66.     }

  67.     /**
  68.      * 发送消息,实践表明,每次浏览器刷新,session会发生变化。
  69.      * @param session
  70.      * @param message
  71.      */
  72.     public static void SendMessage(Session session, String message) {
  73.         try {
  74. //            session.getBasicRemote().sendText(String.format("%s (From Server,Session ID=%s)",message,session.getId()));
  75.             session.getBasicRemote().sendText(message);
  76.         } catch (IOException e) {
  77.             log.error("发送消息出错:{}", e.getMessage());
  78.             e.printStackTrace();
  79.         }
  80.     }

  81.     /**
  82.      * 群发消息
  83.      * @param message
  84.      * @throws IOException
  85.      */
  86.     public static void BroadCastInfo(String message) throws IOException {
  87.         for (Session session : SessionSet) {
  88.             if(session.isOpen()){
  89.                 SendMessage(session, message);
  90.             }
  91.         }
  92.     }

  93.     /**
  94.      * 指定Session发送消息
  95.      * @param sessionId
  96.      * @param message
  97.      * @throws IOException
  98.      */
  99.     public static void SendMessage(String message,String sessionId) throws IOException {
  100.         Session session = null;
  101.         for (Session s : SessionSet) {
  102.             if(s.getId().equals(sessionId)){
  103.                 session = s;
  104.                 break;
  105.             }
  106.         }
  107.         if(session!=null){
  108.             SendMessage(session, message);
  109.         }
  110.         else{
  111.             log.warn("没有找到你指定ID的会话:{}",sessionId);
  112.         }
  113.     }
  114. }
复制代码
4、WebSocketController,主要实现消息群发和一对一发送
  1. package com.cookie.controller;

  2. import com.cookie.server.WebSocketServer;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.RequestMethod;
  5. import org.springframework.web.bind.annotation.RequestParam;
  6. import org.springframework.web.bind.annotation.RestController;

  7. import java.io.IOException;

  8. /**
  9. * @Author : cxq
  10. * @Date : 2020/8/31 16:19
  11. */

  12. @RestController
  13. @RequestMapping("/webSocket")
  14. public class WebSocketController {


  15.     /**
  16.      * 群发消息内容
  17.      *
  18.      * @param message
  19.      * @return
  20.      */
  21.     @RequestMapping(value = "/sendAll", method = RequestMethod.GET)
  22.     public String sendAllMessage(@RequestParam(required = true) String message) {
  23.         try {
  24.             WebSocketServer.BroadCastInfo(message);
  25.         } catch (IOException e) {
  26.             e.printStackTrace();
  27.         }
  28.         return "ok";
  29.     }

  30.     /**
  31.      * 指定会话ID发消息
  32.      *
  33.      * @param message 消息内容
  34.      * @param id      连接会话ID
  35.      * @return
  36.      */
  37.     @RequestMapping(value = "/sendOne", method = RequestMethod.GET)
  38.     public String sendOneMessage(@RequestParam(required = true) String message,
  39.                                  @RequestParam(required = true) String id) {
  40.         try {
  41.             WebSocketServer.SendMessage(message, id);
  42.         } catch (IOException e) {
  43.             e.printStackTrace();
  44.         }
  45.         return "ok";
  46.     }
  47. }
复制代码
5、index.html接收后端发送的消息及展示



  1.    
  2.     websocket测试
  3.    
  4.    



  5. [b]WebSocket测试,客户端接收到的消息如下:[/b]

  6. <br /><br />





复制代码
6、启动项目,访问页面看效果
  访问 localhost:8080,网页展示如下

springboot整合websocket实现消息推送

springboot整合websocket实现消息推送
多看几个页面,页面展示内容都一样,同时后端控制台打印消息如下

springboot整合websocket实现消息推送

springboot整合websocket实现消息推送
接下来,使用postman,依次调用一对一消息推送和群发消息
一对一:http://localhost:8080/webSocket/sendOne?message="这是一条单个消息"&id=1
页面展示如下:

springboot整合websocket实现消息推送

springboot整合websocket实现消息推送
群发消息:http://localhost:8080/webSocket/sendAll?message="这是一条群发消息"
页面展示如下:

springboot整合websocket实现消息推送

springboot整合websocket实现消息推送


相关帖子

扫码关注微信公众号,及时获取最新资源信息!下载附件优惠VIP会员6折;永久VIP4折
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

免责声明:
1、本站提供的所有资源仅供参考学习使用,版权归原著所有,禁止下载本站资源参与商业和非法行为,请在24小时之内自行删除!
2、本站所有内容均由互联网收集整理、网友上传,并且以计算机技术研究交流为目的,仅供大家参考、学习,请勿任何商业目的与商业用途。
3、若您需要商业运营或用于其他商业活动,请您购买正版授权并合法使用。
4、论坛的所有内容都不保证其准确性,完整性,有效性,由于源码具有复制性,一经售出,概不退换。阅读本站内容因误导等因素而造成的损失本站不承担连带责任。
5、用户使用本网站必须遵守适用的法律法规,对于用户违法使用本站非法运营而引起的一切责任,由用户自行承担
6、本站所有资源来自互联网转载,版权归原著所有,用户访问和使用本站的条件是必须接受本站“免责声明”,如果不遵守,请勿访问或使用本网站
7、本站使用者因为违反本声明的规定而触犯中华人民共和国法律的,一切后果自己负责,本站不承担任何责任。
8、凡以任何方式登陆本网站或直接、间接使用本网站资料者,视为自愿接受本网站声明的约束。
9、本站以《2013 中华人民共和国计算机软件保护条例》第二章 “软件著作权” 第十七条为原则:为了学习和研究软件内含的设计思想和原理,通过安装、显示、传输或者存储软件等方式使用软件的,可以不经软件著作权人许可,不向其支付报酬。若有学员需要商用本站资源,请务必联系版权方购买正版授权!
10、本网站如无意中侵犯了某个企业或个人的知识产权,请来信【站长信箱312337667@qq.com】告之,本站将立即删除。
郑重声明:
本站所有资源仅供用户本地电脑学习源代码的内含设计思想和原理,禁止任何其他用途!
本站所有资源、教程来自互联网转载,仅供学习交流,不得商业运营资源,不确保资源完整性,图片和资源仅供参考,不提供任何技术服务。
本站资源仅供本地编辑研究学习参考,禁止未经资源商正版授权参与任何商业行为,违法行为!如需商业请购买各资源商正版授权
本站仅收集资源,提供用户自学研究使用,本站不存在私自接受协助用户架设游戏或资源,非法运营资源行为。
 
在线客服
点击这里给我发消息 点击这里给我发消息 点击这里给我发消息
售前咨询热线
312337667

微信扫一扫,私享最新原创实用干货

QQ|免责声明|小黑屋|依星资源网 ( 鲁ICP备2021043233号-3 )|网站地图

GMT+8, 2025-4-17 06:46

Powered by Net188.com X3.4

邮箱:312337667@qq.com 客服QQ:312337667(工作时间:9:00~21:00)

快速回复 返回顶部 返回列表