springboot业务功能实战(四)告别轮询,websocket的集成使用

简介: springboot业务功能实战(四)告别轮询,websocket的集成使用


后端代码

首先加入pom文件

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
            <!-- <version>1.3.5.RELEASE</version> -->
        </dependency>

加入配置类

@Configuration
public class WebSocketConfig {
    /**
     *  注入ServerEndpointExporter,
     *  这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

加入连接发送消息方法

@Component
@ServerEndpoint("/websocket/{userName}")
// 此注解相当于设置访问URL
public class WebSocket {
    private Session session;
    private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>();
    private static Map<String, Session> sessionPool = new HashMap<String, Session>();
    private final static Logger logger = LoggerFactory.getLogger(LoginIntercept.class);
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userName") String userName) {
        this.session = session;
        webSockets.add(this);
        if (sessionPool.containsKey(userName)) {
            sessionPool.put(userName + String.valueOf(session.getId()), session);
        } else {
            sessionPool.put(userName, session);
        }
        logger.info("【websocket消息】有新的连接,总数为:" + webSockets.size());
    }
    @OnClose
    public void onClose() {
        webSockets.remove(this);
        logger.info("【websocket消息】连接断开,总数为:" + webSockets.size());
    }
    @OnMessage
    public void onMessage(String message) {
        logger.info("【websocket消息】收到客户端消息:" + message);
    }
    /**
     * 功能描述: 此为广播消息
     *
     * @param: [message] (消息)
     * @return: void ()
     */
    public void sendAllMessage(String message) {
        for (WebSocket webSocket : webSockets) {
            logger.info("【websocket消息】广播消息:" + message);
            try {
                if (webSocket.session.isOpen()) {
                    webSocket.session.getAsyncRemote().sendText(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 功能描述:此为单点消息 (发送文本) 现在可以发送给多客户端
     *
     * @param: [userName, message] (接收人,发送消息)
     * @return: void ()
     */
    public void sendTextMessage(String userName, String message) {
        // 遍历sessionPool
        for (String key : sessionPool.keySet()) {
            // 存在当前用户
            if (key.toString().indexOf(userName) != -1) {
                Session session = sessionPool.get(key);
                if (session != null && session.isOpen()) {
                    try {
                        session.getAsyncRemote().sendText(message);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    /**
     * 功能描述: 此为单点消息 (发送文本) 现在可以发送给多客户端
     *
     * @param: [userName, message] (接收人,发送消息)
     * @return: void ()
     */
    public void sendObjMessage(String userName, Object message) {
        // 遍历sessionPool
        for (String key : sessionPool.keySet()) {
            // 存在当前用户
            if (key.toString().indexOf(userName) != -1) {
                Session session = sessionPool.get(key);
                if (session != null && session.isOpen()) {
                    try {
                        session.getAsyncRemote().sendObject(message);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

发送信息

@RestController
@RequestMapping("websocket")
public class WebSocketController {
    @GetMapping("setMessage")
    @ApiOperation(value = "发送信息接口", notes = "发送信息接口")
    public Result
        webSocket(@ApiParam(name = "定时任务日志实体", value = "定时任务日志实体", required = false) @RequestBody MessageVO messageVO) {
        Result result = new Result();
        String userName = messageVO.getUserName();
        String message = messageVO.getMessage();
        WebSocket webSocket = new WebSocket();
        webSocket.sendTextMessage(userName, message);
        return result;
    }
}

前段代码

import sysConfig from "../config";
import {Notification} from 'element-ui';
import {EVENT_TYPE} from "../const";
export function openSocket(userId) {
  let ws = new WebSocket(`${sysConfig.SOCKET_URL}/${userId}`);
  // let ws = new WebSocket(`ws://121.40.165.18:8800`);
  ws.onopen = function (evt) {
    Notification({
      title: '欢迎回来!',
      message: `${sysConfig.SOCKET_URL}/${userId}`
    });
  };
  ws.onmessage = function (e) {
    console.log(typeof e.data);
    try{
      if(e.data!=undefined || e.data!=null){
        let json= JSON.parse(e.data);
        Notification({
          title: json.messageTitle,
          message: json.messageText
        });
        //通知页面更新
        window.postMessage(EVENT_TYPE.updateMessage,'/');
      }
    }catch(err){
        console.log("webSocke异常,异常信息:"+err)
    }
    //ws.close();
  };
  ws.onclose = function (evt) {
    console.log('Connection closed.');
  };
}


相关文章
|
Java
springboot业务功能实战(七)手把手教你使用阿里云短信
模板签名的枚举类 进入阿里云平台 进入短信服务模块 在以下·位置添加签名和模板(格式一定按照要求填写 审批的比较严格)
373 0
springboot业务功能实战(七)手把手教你使用阿里云短信
|
Java
springboot业务功能实战(四)告别轮询,websocket的集成使用
springboot业务功能实战(四)告别轮询,websocket的集成使用
297 0
|
4月前
|
JavaScript 安全 Java
如何使用 Spring Boot 和 Ant Design Pro Vue 实现动态路由和菜单功能,快速搭建前后端分离的应用框架
本文介绍了如何使用 Spring Boot 和 Ant Design Pro Vue 实现动态路由和菜单功能,快速搭建前后端分离的应用框架。首先,确保开发环境已安装必要的工具,然后创建并配置 Spring Boot 项目,包括添加依赖和配置 Spring Security。接着,创建后端 API 和前端项目,配置动态路由和菜单。最后,运行项目并分享实践心得,包括版本兼容性、安全性、性能调优等方面。
257 1
|
24天前
|
JavaScript Java 测试技术
基于SpringBoot+Vue实现的留守儿童爱心网站设计与实现(计算机毕设项目实战+源码+文档)
博主是一位全网粉丝超过100万的CSDN特邀作者、博客专家,专注于Java、Python、PHP等技术领域。提供SpringBoot、Vue、HTML、Uniapp、PHP、Python、NodeJS、爬虫、数据可视化等技术服务,涵盖免费选题、功能设计、开题报告、论文辅导、答辩PPT等。系统采用SpringBoot后端框架和Vue前端框架,确保高效开发与良好用户体验。所有代码由博主亲自开发,并提供全程录音录屏讲解服务,保障学习效果。欢迎点赞、收藏、关注、评论,获取更多精品案例源码。
59 10
|
25天前
|
JavaScript Java 测试技术
基于SpringBoot+Vue实现的家政服务管理平台设计与实现(计算机毕设项目实战+源码+文档)
面向大学生毕业选题、开题、任务书、程序设计开发、论文辅导提供一站式服务。主要服务:程序设计开发、代码修改、成品部署、支持定制、论文辅导,助力毕设!
43 8
|
25天前
|
JavaScript 搜索推荐 Java
基于SpringBoot+Vue实现的家乡特色推荐系统设计与实现(源码+文档+部署)
面向大学生毕业选题、开题、任务书、程序设计开发、论文辅导提供一站式服务。主要服务:程序设计开发、代码修改、成品部署、支持定制、论文辅导,助力毕设!
55 8
|
25天前
|
JavaScript NoSQL Java
基于SpringBoot+Vue实现的大学生就业服务平台设计与实现(系统源码+文档+数据库+部署等)
面向大学生毕业选题、开题、任务书、程序设计开发、论文辅导提供一站式服务。主要服务:程序设计开发、代码修改、成品部署、支持定制、论文辅导,助力毕设!
63 6
|
25天前
|
JavaScript Java 测试技术
基于Java+SpringBoot+Vue实现的车辆充电桩系统设计与实现(系统源码+文档+部署讲解等)
面向大学生毕业选题、开题、任务书、程序设计开发、论文辅导提供一站式服务。主要服务:程序设计开发、代码修改、成品部署、支持定制、论文辅导,助力毕设!
56 6
|
25天前
|
JavaScript NoSQL Java
基于SpringBoot+Vue的班级综合测评管理系统设计与实现(系统源码+文档+数据库+部署等)
✌免费选题、功能需求设计、任务书、开题报告、中期检查、程序功能实现、论文辅导、论文降重、答辩PPT辅导、会议视频一对一讲解代码等✌
40 4
|
25天前
|
JavaScript Java 测试技术
基于SpringBoot+Vue实现的高校食堂移动预约点餐系统设计与实现(源码+文档+部署)
面向大学生毕业选题、开题、任务书、程序设计开发、论文辅导提供一站式服务。主要服务:程序设计开发、代码修改、成品部署、支持定制、论文辅导,助力毕设!
69 3

热门文章

最新文章