首页 > 其他分享 >ruoyi整合WebSocket

ruoyi整合WebSocket

时间:2023-04-21 19:34:07浏览次数:28  
标签:WebSocket log userId ruoyi session 整合 websocket message public

https://www.cnblogs.com/SjhCode/p/WebSocket.html

 

ruoyi整合WebSocket

这里使用WebSocket目的:向前端推送实时消息,配合ActiveMQ接入三方使用的

导入maven依赖

 
 <!-- WebSocket -->
        <dependency>
            <groupId>org.java-websocket</groupId>
            <artifactId>Java-WebSocket</artifactId>
            <version>1.5.1</version>
        </dependency>
        <dependency>
            <groupId>javax.websocket</groupId>
            <artifactId>javax.websocket-api</artifactId>
            <version>1.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
 

 注册配置webSocket类

 
package com.ruoyi.common.websocket;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

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

 webSocket工具类

package com.ruoyi.common.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * webSocket工具
 */
@Component
@ServerEndpoint("/webSocket")
public class WebSocket {
    private Session session;


    private final static Logger log = LoggerFactory.getLogger(WebSocket.class);

    private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<>();

    //Session 的生命周期,onOpen -> onMessage -> onClose
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);
        log.info("【websocket消息】有新的连接, 总数:{}", webSocketSet.size());
    }

    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        log.info("【websocket消息】连接断开, 总数:{}", webSocketSet.size());
    }

    @OnMessage
    public void onMessage(String message) {
        log.info("【websocket消息】收到客户端发来的消息:{}", message);
    }

    public void sendMessage(String message) {
        for (WebSocket webSocket: webSocketSet) {
            log.info("【websocket消息】广播消息, message={}", message);
            System.out.println(message);
            try {
                webSocket.session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
 

 

使用时,从三方获取的推送信息,处理完由webSocket推送给前端

webSocket.sendMessage(JSON.toJSONString(XXXDto));

 注意:有时候和前端对接会出现异常java.io.EOFException: null ,可能是未配置错误处理,可以加上onError方法

 
    /**
     * 配置错误信息处理
     * @param session
     * @param t
     */
    @OnError
    public void one rror(Session session, Throwable t) {
        //什么都不想打印都去掉就好了
        log.info("【websocket消息】出现未知错误 ");
        //打印错误信息,如果你不想打印错误信息,去掉就好了
        //这里打印的也是  java.io.EOFException: null
        t.printStackTrace();
    }
 

连接时带入userId的写法,将存储webSocket的Set换成Map,由前端传入。(单点发送)

/**
 * webSocket工具
 */
@Component
@ServerEndpoint("/webSocket/{userId}")
public class WebSocket {
    private Session session;


    private final static Logger log = LoggerFactory.getLogger(WebSocket.class);

    //当前在线人数
    private static int onlineCount = 0;
    private static ConcurrentHashMap<Long, WebSocket> webSocketMap = new ConcurrentHashMap<>();
    private Long userId = 0L;

    //Session 的生命周期,onOpen -> onMessage -> onClose
    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session,@PathParam("userId") Long userId) {
        this.session = session;
        this.userId=userId;
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            webSocketMap.put(userId,this);
            //加入set中
        }else{
            webSocketMap.put(userId,this);
            //加入set中
            addOnlineCount();
            //在线数加1
        }
        log.info("用户连接:"+userId+",当前在线人数为:" + getOnlineCount());
        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            log.error("用户:"+userId+",网络异常!!!!!!");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            //从set中删除
            subOnlineCount();
        }
        log.info("用户退出:"+userId+",当前在线人数为:" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("用户消息:"+userId+",报文:"+message);
        //可以群发消息
        //消息保存到数据库、redis
        if(StringUtils.isNotEmpty(message)){
            try {
                //解析发送的报文
                JSONObject jsonObject = JSON.parseObject(message);
                //追加发送人(防止串改)
                jsonObject.put("fromUserId",this.userId);
                String toUserId=jsonObject.getString("toUserId");
                //传送给对应toUserId用户的websocket
                if(StringUtils.isNotBlank(toUserId)&&webSocketMap.containsKey(toUserId)){
                    webSocketMap.get(toUserId).sendMessage(jsonObject.toJSONString());
                }else{
                    log.error("请求的userId:"+toUserId+"不在该服务器上");
                    //否则不在这个服务器上,发送到mysql或者redis
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void one rror(Session session, Throwable error) {
        log.error("用户错误:"+this.userId+",原因:"+error.getMessage());
        error.printStackTrace();
    }
    /**
     * 实现服务器主动推送,广播
     */
    public void sendMessage(String message) throws IOException {
        log.info("广播消息为{}",message);
        this.session.getBasicRemote().sendText(message);
    }


    /**
     * 发送自定义消息
     * */
    public void sendInfo(String message,@PathParam("userId") Long userId) throws IOException {
        log.info("发送消息到:"+userId+",报文:"+message);
        if(userId!=null&&webSocketMap.containsKey(userId)){
            webSocketMap.get(userId).sendMessage(message);
        }else{
            log.error("用户"+userId+",不在线!");
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocket.onlineCount--;
    }
}
 

标签:WebSocket,log,userId,ruoyi,session,整合,websocket,message,public
From: https://www.cnblogs.com/chuangsi/p/17341515.html

相关文章

  • springboot框架快速整合websocket
    1、【pom.xml】<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency>2、【MsgType.java】/***@authorJHL*2019-08-109:56*/publicenumM......
  • 若依RuoYi框架浅析 基础篇①——日志logs本地保存
    文章目录日志保存位置在/home/ruoyi/logs/[root@iZ2ze30dygwd6yh7gu6lskZlogs]#cd/home/ruoyi/logs/[root@iZ2ze30dygwd6yh7gu6lskZlogs]#lssys-error.2021-02-28.logsys-error.logsys-info.2021-02-28.logsys-info.2021-03-01.logsys-info.logsys-user.2021-0......
  • 整合swagger2
    添加配置类importcom.google.common.base.Predicates;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importspringfox.documentation.builders.ApiInfoBuilder;importspringfox.documentation.build......
  • ztree初始化时选中(ruoyi版)
    ruoyi版本:4.6.0问题描述将后台传入的参数放到$.tree中,当ztree的Node中checked为true时,Node默认为选中,目前前台调用代码varurl=ctx+"获得List<Ztree>的URL";varoptions={url:url,expandLevel:2,beforeClick:function(treeId,treeNode,clickFlag){......
  • Kubuesphere部署Ruoyi(三):持久化存储配置
    按照如下教程配置NFS先服务器:https://kubesphere.io/zh/docs/v3.3/reference/storage-system-installation/nfs-server/后客户端:https://kubesphere.io/zh/docs/v3.3/installing-on-linux/persistent-storage-configurations/install-nfs-client/按照链接操作以后,在客户端上......
  • 使用Fiddler抓取WebSockets协议包
    背景服务端通过SignalR用WebSockets通讯方式,与显示屏进行交互,除了显示屏软件上日志入口,也能通过抓包抓取对应报文。同时,可通过工具模拟与显示屏软件推送信息。那HTTP和WebSocket有什么区别呢?引用网友写的描述HTTP建立在TCP协议基础上而WebSocket通常建立在TCP上,也说明了为什......
  • Nacos笔记(五):Nacos集群整合Nginx
    前言Nginx搭建,参考:Linux安装Nginx。1、Nginx配置添加nacos集群,调整端口与服务名,并设置代理,详情如下:   配置详情如下http{includemime.types;default_typeapplication/octet-stream;sendfileon;keepalive_timeout......
  • 使用cistrome BETA整合ChIPseq和RNAseq
     写在前面:在获得同一个样本多种测序数据后,一个自然的目标就是整合,general的问题就是:表观是如何影响转录的?基本的数据种类:TFbinding,ChIP-seq和Cut&RunHistoneprofile,ChIP-seq和Cut&RunOpenchromatin,ATAC-seqGeneexpression,RNA-seq具体的问题就是:表观转录调控是如......
  • Chatgpt 帮忙写的脚本_使用powershell 写一段代码,功能实现将指定目录下多个csv 文件整
    需求:使用powershell写一段代码,功能实现将指定目录下多个csv文件整合成一个csv文件以下是使用PowerShell实现将指定目录下多个CSV文件合并为一个的示例代码:powershell点击查看代码#设置源目录和目标文件路径$sourceDirectory="C:\path\to\csv\files"$targetFilePa......
  • Kubuesphere部署Ruoyi(二):部署kubesphere
    先决条件:更换DNS更换apt的镜像源Ubuntu下永久性修改DNSvi/etc/systemd/resolved.confDNS字段取消注释,并修改DNS为223.5.5.5223.5.5.5是一个IP地址,是AlibabaCloud提供的免费DNS服务器的IP地址。修改后保存。systemctlrestartsystemd-resolved清华镜像源https://m......