若依springcloud 前后端分离 集成 websocket

添加websocket 依赖

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

网管配置服务转发

# websocket模块
        #服务名称
        - id: ruoyi-websocket
          #转发的服务
          uri: lb:ws://ruoyi-system
          #转发设置
          predicates:
            - Path=/socket/**
          #请求地址后一位,如:/socket/xxx/xx  去掉socket = /xxx/xx
          filters:
            - StripPrefix=1

如图
若依springcloud 前后端分离 集成 websocket_第1张图片
添加配置

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();
    }
}

连接代码

import com.fasterxml.jackson.annotation.JsonBackReference;
import com.ruoyi.common.core.config.systemConfig;
import com.ruoyi.common.core.utils.SpringUtils;
import com.ruoyi.common.redis.service.RedisService;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.io.Serializable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@ServerEndpoint(value = "/websocket/{userName}")
@Component
public class WebSocketService implements Serializable {

    //concurrent包的线程安全Set,用来存放每个客户端对应的WebSocketServer对象。
    @JsonBackReference
    private static Map<String, WebSocketService> webSocketMap = new ConcurrentHashMap<>();

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

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userName") String userName) {
        this.session = session;
        this.userName = userName;
        webSocketMap.put(userName, this);
        System.err.println("----------------------------------------------------------------------------");
        System.err.println("用户连接:" + userName + ":" + userName + ",当前在线人数为:" + webSocketMap.size());
        sendMessage("来自后台的反馈:连接成功");
        webSocketMap.forEach((k, v) -> System.err.println(k));
    }


    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(@PathParam("userName") String userName) {
        if (webSocketMap.containsKey(userName)) {
            webSocketMap.remove(userName);
        }
        System.err.println("----------------------------------------------------------------------------");
        System.err.println(userName + "用户退出,当前在线人数为:" + webSocketMap.size());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        System.err.println("收到用户消息:" + userName + ",报文:" + message);
        //可以群发消息
        //消息保存到数据库、redis
        if (message != null) System.err.println("");
    }

    /**
     * 连接失败调用方法
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.err.println("用户错误:" + this.userName + ",原因:" + error.getMessage());
        error.printStackTrace();
    }


    /**
     * 连接服务器成功后主动推送
     */
    public void sendMessage(String message) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    /**
     * 向指定客户端发送消息
     * 

* // * @param userName * //* @param message */ public static void sendMessage(String userName, String message) { try { WebSocketService webSocketService = webSocketMap.get(userName); if (webSocketService != null) { webSocketService.getSession().getBasicRemote().sendText(message); } } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } } //下面方法根据自己情况 删 留 public Session getSession() { return session; } public void setSession(Session session) { this.session = session; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public static Map<String, WebSocketService> getWebSocketMap() { return webSocketMap; } public static void setWebSocketMap(Map<String, WebSocketService> webSocketMap) { WebSocketService.webSocketMap = webSocketMap; } public static void put(String key, WebSocketService data) { webSocketMap.put(key, data); } public static WebSocketService get(String key) { return webSocketMap.get(key); } public static void del(String key) { webSocketMap.remove(key); }

前端

 path: "ws://127.0.0.1:8080/socket/websocket/" + this.$store.state.user.name,
 socket: "",

若依springcloud 前后端分离 集成 websocket_第2张图片

 //建立连接
    init: function () {
      if (typeof (WebSocket) === "undefined") {
        alert("您的浏览器不支持socket")
      } else {
        // 实例化socket
        this.socket = new WebSocket(this.path)
        // 监听socket连接
        this.socket.onopen = this.openMsg
        // 监听socket错误信息
        this.socket.onerror = this.error
        // 监听socket消息
        this.socket.onmessage = this.getMessage
         // 监听断开连接
        this.socket.onclose = this.getOnclose;
      }
    },
    //连接成功
    openMsg: function () {
      this.$notify({
        title: '成功',
        message: 'socket连接成功',
        type: 'success'
      });
    },
    //连接失败
    error: function () {
      this.$notify.error({
        title: '错误',
        message: 'socket连接错误'
      });
    },
    //接收后台发送的消息
    getMessage: function (msg) {
      this.addTable(msg);
    },
    //用户发送消息
    send: function () {
      /*发送数据*/
      this.socket.send("")
    },
    close: function () {
      /*关闭连接*/
      this.socket.close()
      console.log("socket已经关闭")
    },
     getOnclose(){
      
    },

在页面打开的时候就建立连接
若依springcloud 前后端分离 集成 websocket_第3张图片
页面关闭的时候销毁连接
在这里插入图片描述
最后要打开security白名单,要不然访问不到后端,根据自己路径填写
若依springcloud 前后端分离 集成 websocket_第4张图片

你可能感兴趣的:(java,web开发,java,java-ee,spring)