最近想起之前项目里面的一个实现,是关于订阅推送的,当粉丝订阅了大V或者说作者发布的内容被评论和点赞之后,对应的用户会受到通知,当然,本身系统用户并不多,所以直接采用的是轮训的方式,由前端这边定时向后端发起接口请求,获取消息推送,无疑呢,此种方式也可以解决问题,但是大部分请求基本无用,白白浪费带宽和网络资源。

今天难得媳妇儿带孩子回娘家了,下班到家也无事,便想着整理下前后端通过websocket实现消息推送的方式。当然,前端这块,主要采用原始的js通过websocket的方式获取消息,在微信公众号和支付宝小程序开发中都有相应的onWebSocekt方式,有兴趣的同学可以自行学习。

废话不多说,开始啃代码。

1、pom.xml

        <dependency>            <groupId>org.springframework.bootgroupId>            <artifactId>spring-boot-starter-websocketartifactId>        dependency>                <dependency>            <groupId>org.springframework.bootgroupId>            <artifactId>spring-boot-starter-thymeleafartifactId>        dependency>

2、application.yml

server:  port: 8080spring:  thymeleaf:    cache: false # 开发时关闭缓存,不然没法看到实时页面    mode: HTML # 用非严格的 HTML    encoding: UTF-8    servlet:      content-type: text/html

3、WebSocketServer,实现前后端的长连接

package com.cookie.server;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Component;import javax.annotation.PostConstruct;import javax.websocket.*;import javax.websocket.server.ServerEndpoint;import java.io.IOException;import java.util.concurrent.CopyOnWriteArraySet;import java.util.concurrent.atomic.AtomicInteger;/** * @Author : cxq * @Date : 2020/8/31 15:50 */// 前端通过该连接与后端保持交互@ServerEndpoint(value = "/server")@Componentpublic class WebSocketServer {    @PostConstruct    public void init() {        System.out.println("websocket 加载");    }    private static Logger log = LoggerFactory.getLogger(WebSocketServer.class);    private static final AtomicInteger OnlineCount = new AtomicInteger(0);    // concurrent包的线程安全Set,用来存放每个客户端对应的Session对象。    private static CopyOnWriteArraySet SessionSet = new CopyOnWriteArraySet();    /**     * 连接建立成功调用的方法     */    @OnOpen    public void onOpen(Session session) {        SessionSet.add(session);        int cnt = OnlineCount.incrementAndGet(); // 在线数加1        log.info("有连接加入,当前连接数为:{}", cnt);        SendMessage(session, "连接成功");    }    /**     * 连接关闭调用的方法     */    @OnClose    public void onClose(Session session) {        SessionSet.remove(session);        int cnt = OnlineCount.decrementAndGet();        log.info("有连接关闭,当前连接数为:{}", cnt);    }    /**     * 收到客户端消息后调用的方法     *     * @param message     *            客户端发送过来的消息     */    @OnMessage    public void onMessage(String message, Session session) {        log.info("来自客户端的消息:{}",message);        SendMessage(session, "收到消息,消息内容:"+message);    }    /**     * 出现错误     * @param session     * @param error     */    @OnError    public void onError(Session session, Throwable error) {        log.error("发生错误:{},Session ID:{}",error.getMessage(),session.getId());        error.printStackTrace();    }    /**     * 发送消息,实践表明,每次浏览器刷新,session会发生变化。     * @param session     * @param message     */    public static void SendMessage(Session session, String message) {        try {//            session.getBasicRemote().sendText(String.format("%s (From Server,Session ID=%s)",message,session.getId()));            session.getBasicRemote().sendText(message);        } catch (IOException e) {            log.error("发送消息出错:{}", e.getMessage());            e.printStackTrace();        }    }    /**     * 群发消息     * @param message     * @throws IOException     */    public static void BroadCastInfo(String message) throws IOException {        for (Session session : SessionSet) {            if(session.isOpen()){                SendMessage(session, message);            }        }    }    /**     * 指定Session发送消息     * @param sessionId     * @param message     * @throws IOException     */    public static void SendMessage(String message,String sessionId) throws IOException {        Session session = null;        for (Session s : SessionSet) {            if(s.getId().equals(sessionId)){                session = s;                break;            }        }        if(session!=null){            SendMessage(session, message);        }        else{            log.warn("没有找到你指定ID的会话:{}",sessionId);        }    }}

4、WebSocketController,主要实现消息群发和一对一发送

package com.cookie.controller;import com.cookie.server.WebSocketServer;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import java.io.IOException;/** * @Author : cxq * @Date : 2020/8/31 16:19 */@RestController@RequestMapping("/webSocket")public class WebSocketController {    /**     * 群发消息内容     *     * @param message     * @return     */    @RequestMapping(value = "/sendAll", method = RequestMethod.GET)    public String sendAllMessage(@RequestParam(required = true) String message) {        try {            WebSocketServer.BroadCastInfo(message);        } catch (IOException e) {            e.printStackTrace();        }        return "ok";    }    /**     * 指定会话ID发消息     *     * @param message 消息内容     * @param id      连接会话ID     * @return     */    @RequestMapping(value = "/sendOne", method = RequestMethod.GET)    public String sendOneMessage(@RequestParam(required = true) String message,                                 @RequestParam(required = true) String id) {        try {            WebSocketServer.SendMessage(message, id);        } catch (IOException e) {            e.printStackTrace();        }        return "ok";    }}

5、index.html接收后端发送的消息及展示

<html lang="en" xmlns:th="http://www.thymeleaf.org"><head>    <meta charset="UTF-8">    <title>websocket测试title>    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js">script>    <style type="text/css">        h3,h4{            text-align:center;        }style>head><body><h3>WebSocket测试,客户端接收到的消息如下:h3><textarea id = "messageId" readonly="readonly" cols="150" rows="30" >textarea><script type="text/javascript">    var socket;    if (typeof (WebSocket) == "undefined") {        console.log("遗憾:您的浏览器不支持WebSocket");    } else {        console.log("恭喜:您的浏览器支持WebSocket");        //实现化WebSocket对象        //指定要连接的服务器地址与端口建立连接        //注意ws、wss使用不同的端口。我使用自签名的证书测试,        //无法使用wss,浏览器打开WebSocket时报错        //ws对应http、wss对应https。        socket = new WebSocket("ws://localhost:8080/server");        //连接打开事件        socket.onopen = function() {            console.log("Socket 已打开");            socket.send("消息发送测试(From Client)");        };        //收到消息事件        socket.onmessage = function(msg) {            $("#messageId").append(msg.data+ "\n");            console.log(msg.data  );        };        //连接关闭事件        socket.onclose = function() {            console.log("Socket已关闭");        };        //发生了错误事件        socket.onerror = function() {            alert("Socket发生了错误");        }        //窗口关闭时,关闭连接        window.unload=function() {            socket.close();        };    }script>body>html>

6、启动项目,访问页面看效果

访问 localhost:8080,网页展示如下

多看几个页面,页面展示内容都一样,同时后端控制台打印消息如下

接下来,使用postman,依次调用一对一消息推送和群发消息

一对一:http://localhost:8080/webSocket/sendOne?message="这是一条单个消息"&id=1

页面展示如下:

群发消息:http://localhost:8080/webSocket/sendAll?message="这是一条群发消息"

页面展示如下:

thymeleaf 消息推送_SpringBoot整合WebSocket实现消息推送相关推荐

  1. springboot定时发送短信_springboot 整合websocket实现消息推送(主动推送,具体用户推送,群发,定时推送)...

    websocket springboot 整合websocket实现消息推送(主动推送,具体用户推送,群发,定时推送) 使用WebSocket构建交互式Web应用程序 本指南将引导您完成创建" ...

  2. java整合消息推送_SpringMVC整合websocket实现消息推送及触发功能

    本文为大家分享了SpringMVC整合websocket实现消息推送,供大家参考,具体内容如下 1.创建websocket握手协议的后台 (1)HandShake的实现类 /** *Project N ...

  3. springboot整合websocket进行消息推送

    什么是websocket? WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议,使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据. ...

  4. SpringMVC整合websocket实现消息推送及触发

    2019独角兽企业重金招聘Python工程师标准>>> 1.创建websocket握手协议的后台 (1)HandShake的实现类 [java] view plain copy /* ...

  5. springboot整合websocket实现消息推送

    springboot整合websocket 1.WebSocket介绍与原理 介绍:WebSocket是HTML5一种新的协议.它实现了浏览器与服务器全双工通信.一开始的握手需要借助HTTP请求完成. ...

  6. python websocket实现消息推送_python Django websocket 实时消息推送

    [实例简介] Django websocket 实时消息推送 服务端主动推送 调用 send(username, title, data, url) username:用户名 title:消息标题 d ...

  7. thymeleaf 消息推送_Springboot集成WebSocket+Thymeleaf+Echarts完成数据的实时推送

    完成效果图: 项目准备提要: com.github.pagehelper pagehelper-spring-boot-starter 1.2.5 org.springframework.boot s ...

  8. uniapp接收服务器消息,【教程】uniapp websocket实现消息推送

    部分开发者在使用uniapp的过程中会用到websocket,但是uniapp框架提供的websocket服务并不是尽善尽美. 我在这里为大家介绍一款第三方的websocket推送服务:GoEasy, ...

  9. 后端 消息 转发_springCloud 后端使用webSocket向前端推送消息

    1.webSocket webSocket长连接是一种在单个tcp连接上进行全双工通信的协议,允许双向数据推送.一般微服务提供的restful API只是对前端请求做出相应.使用webSocket可以 ...

  10. SpringBoot2.x 整合websocket 消息推送,单独发送信息,群发信息

    根据公司需求在SpringBoot项目中集成站内信,于是,我做了一个SpringBoot2.x 整合websocket 消息推送,给指定用户发送信息和群发信息即点点对方式和广播方式2种模式. 文章目录 ...

最新文章

  1. 用Python分析本山大叔鬼畜视频为啥这么火
  2. java io 读取配置文件_java读取配置文件 - tomzhao2008的个人空间 - OSCHINA - 中文开源技术交流社区...
  3. error 4 in libc-2.12.so 解决办法
  4. 深入理解PHP中赋值与引用
  5. 【NIO】之IO和NIO的区别
  6. JAVA设计模式之【单例模式】
  7. PHP用gd库给图片添加水印,php用GD库给图片添加水印
  8. 初学者看看PHP explode() 函数 第6篇
  9. 入行AI,你需要一本Python机器学习入门,赶紧收藏!
  10. 如何在JavaScript中使用when()有条件地更改值
  11. Python | 多种编码文件(中文)乱码问题解决
  12. 二叉树查找最大最小值c语言,用C语言实现二叉排序树查找小于关键字key的最大节点的函数...
  13. python画柱状图-Python绘制柱状图
  14. 学生成绩管理系统源码
  15. 看完这篇解决你99%的运维安全陋习,快别踩坑了!
  16. 常用软件国内源镜像地址大全
  17. 模型加速(矩阵元素优化和cuba使用)
  18. oracle的并行原理
  19. 深度学习笔记(四) cost function来源和证明
  20. dedecms 无法采集 php.ini,解决织梦DEDECMS换空间不能采集的问题

热门文章

  1. iptables数据包、连接标记模块MARK/CONNMARK的使用(打标签)
  2. Spring配置属性文件
  3. VS2010/MFC设置对话框控件的Tab顺序
  4. linux vi ^M符号
  5. 智能优化算法:花授粉算法-附代码
  6. 【LeetCode】【数组】题号:*645,重复数字和缺失数字
  7. Pytorch——计算机视觉工具包:torchvision
  8. 初步接触Java中的Lambda表达式
  9. AAAI论文Joint Extraction of Entities and Overlapping Relations Using Position-Attentive Sequence阅读笔记
  10. Android RootTrustManager 证书校验简单分析