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业务功能实战(七)手把手教你使用阿里云短信
模板签名的枚举类 进入阿里云平台 进入短信服务模块 在以下·位置添加签名和模板(格式一定按照要求填写 审批的比较严格)
642 0
springboot业务功能实战(七)手把手教你使用阿里云短信
|
Java
springboot业务功能实战(四)告别轮询,websocket的集成使用
springboot业务功能实战(四)告别轮询,websocket的集成使用
508 0
|
JavaScript Java 关系型数据库
基于springboot的项目管理系统
本文探讨项目管理系统在现代企业中的应用与实现,分析其研究背景、意义及现状,阐述基于SSM、Java、MySQL和Vue等技术构建系统的关键方法,展现其在提升管理效率、协同水平与风险管控方面的价值。
基于springboot的儿童家长教育能力提升学习系统
本系统聚焦儿童家长教育能力提升,针对家庭教育中理念混乱、时间不足、个性化服务缺失等问题,构建科学、系统、个性化的在线学习平台。融合Spring Boot、Vue等先进技术,整合优质教育资源,提供高效便捷的学习路径,助力家长掌握科学育儿方法,促进儿童全面健康发展,推动家庭和谐与社会进步。
|
JavaScript Java 关系型数据库
基于springboot的古树名木保护管理系统
本研究针对古树保护面临的严峻挑战,构建基于Java、Vue、MySQL与Spring Boot技术的信息化管理系统,实现古树资源的动态监测、数据管理与科学保护,推动生态、文化与经济可持续发展。
2025基于springboot的校车预定全流程管理系统
针对传统校车管理效率低、信息不透明等问题,本研究设计并实现了一套校车预定全流程管理系统。系统采用Spring Boot、Java、Vue和MySQL等技术,实现校车信息管理、在线预定、实时监控等功能,提升学校管理效率,保障学生出行安全,推动教育信息化发展。
|
人工智能 Java 关系型数据库
基于springboot的画品交流系统
本项目构建基于Java+Vue+SpringBoot+MySQL的画品交流系统,旨在解决传统艺术交易信息不透明、流通受限等问题,融合区块链与AI技术,实现画品展示、交易、鉴赏与社交一体化,推动艺术数字化转型与文化传播。
|
JavaScript Java 关系型数据库
基于springboot的高校运动会系统
本系统基于Spring Boot、Vue与MySQL,实现高校运动会报名、赛程安排及成绩管理的全流程信息化,提升组织效率,杜绝信息错漏与冒名顶替,推动体育赛事智能化发展。
基于springboot的大学生兼职系统
本课题针对大学生兼职信息不对称、权益难保障等问题,研究基于Spring Boot、Vue、MySQL等技术的兼职系统,旨在构建安全、高效、功能完善的平台,提升大学生就业竞争力与兼职质量。