RuoYi前后端分离微服务版集成WebSocket

本文详细介绍了在RuoYi前后端分离微服务架构中如何集成WebSocket,从新建子模块到后端配置、服务编写,再到前端Vue的实现与测试,提供了完整的步骤与测试方法。

RuoYi前后端分离微服务版集成WebSocket

新建模块

1.在common模块下新建子模块

在这里插入图片描述
可以复制一份本模块其他的子模块,把除了src和pom之外的文件全删除

2.在common父模块中引入websocket子模块

在这里插入图片描述

后端

1. 引入依赖

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

2.编写配置类

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

@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

3.编写服务类

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @ Description:
 * @ ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
 * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
 */
@Component
@ServerEndpoint("/api/websocket/{sid}")
public class WebSocketServer {

    private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);
    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;

    //接收sid
    private String sid = "";

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        this.sid = sid;
        addOnlineCount();           //在线数加1
        try {
            sendMessage("conn_success");
            log.info("有新窗口开始监听:[ " + sid + " ],当前在线人数为:" + getOnlineCount());
        } catch (IOException e) {
            log.error("websocket IO Exception");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();              //在线数减1
        //断开连接情况下,更新主板占用情况为释放
        log.info("释放的sid为:"+sid);
        //这里写你 释放的时候,要处理的业务
        log.info("有一连接关闭!当前在线人数为" + getOnlineCount());

    }

    /**
     * 收到客户端消息后调用的方法
     * @ Param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到来自窗口[ " + sid + " ]的信息:" + message);
        //群发消息测试,处理收到消息的业务逻辑
        try {
            sendInfo(Math.random()+"ml",sid);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * @ Param session
     * @ Param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("websocket 发生错误");
        error.printStackTrace();
    }

    /**
     * 群发消息
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 判断sid发送消息
     */
    public static void sendInfo(String message,  String sid) throws IOException {
        log.info("推送消息到窗口[ " + sid + " ],推送内容:" + message);
        for (WebSocketServer item : webSocketSet) {
            try {
                //这里可以设定只推送给这个sid的,为null则全部推送
                if (sid == null) {
                // item.sendMessage(message);
                } else if (item.sid.equals(sid)) {
                    item.sendMessage(message);
                }
            } catch (IOException e) {
                continue;
            }
        }
    }

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

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

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

    public static CopyOnWriteArraySet<WebSocketServer> getWebSocketSet() {
        return webSocketSet;
    }
}

4.自动化配置

在resources\META-INF\spring文件夹下的org.springframework.boot.autoconfigure.AutoConfiguration.imports文件中配置以上两个类
在这里插入图片描述

5.后端测试

1.在modules-system模块下引入pom,
在这里插入图片描述
2.在gateway网关配置文件中配置路径白名单
3.到此就可以直接在websocket在线测试网站中自行测试了,
测试地址为:网关IP:端口/网关中配置的system模块路由/api/websocket/{sid}
或者直接访问system模块:system模块IP:端口/api/websocket/{sid}
在这里插入图片描述

vue前端测试代码

1.template中添加

<!-- websocket测试  start -->
  <div>
    <el-row :gutter="10" >
      <el-col :span="4" :xs="24">
         <el-button
            type="primary"
            size="mini"
            @click="send"
            >测试WebSocket
        </el-button>
      </el-col>
      <el-col :span="4" :xs="24">
        <div class="head-container">
            <el-input
              v-model="message"
              clearable
              size="small"
              style="margin-bottom: 20px"
            />
        </div>
      </el-col>
    </el-row> 
  </div>
  <!-- websocket测试   end -->

2.data中添加

//======websocket测试=======start
url: "ws://127.0.0.1:8080/system/api/websocket/message",
message: "",
ws: null,
//======websocket测试========end

3.methods中添加

//======websocket测试=======start
    join() {
      this.ws = new WebSocket(this.url);
      //非Vue所管理的函数,需要保存this
      const v_this = this;
      this.ws.onopen = function (event) {
        v_this.message = v_this.message + "已经打开连接!" + "\n";
      };
      this.ws.onmessage = function (event) {
        v_this.message = event.data + "\n";
      };
      this.ws.onclose = function (event) {
        v_this.message = v_this.message + "已经关闭连接!" + "\n";
      };
    },
    exit() {
      if (this.ws) {
        this.ws.close();
        this.ws = null;
      }
    },
    send() {
      if (this.ws) {
        this.ws.send(this.message);
      } else {
        alert("未连接到服务器");
      }
    },
//======websocket测试========end
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值