首页 > 其他分享 >vue+webSocket+springCloud消息推送交互

vue+webSocket+springCloud消息推送交互

时间:2023-04-01 23:32:31浏览次数:47  
标签:vue websocket log springCloud userId import webSocket 连接

一、后台代码:

1、pom里面加上依赖;

<!--webSocket坐标依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
            <version>2.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty.websocket</groupId>
            <artifactId>websocket-server</artifactId>
            <version>9.4.7.v20170914</version>
            <scope>test</scope>
        </dependency>

2、webSocket配置文件

/**
 * @description: webSocket配置类
 * @author: xgs
 * @date: 2020/2/11 11:14
 */
@Configuration
public class WebSocketConfig {
    /**
     * 注入ServerEndpointExporter,
     * 这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

3、webSocket主类

package com.yzcx.project.service.webSocket;

import com.yzcx.common.constant.RedisKeyConstants;
import com.yzcx.onlinecar.util.RedisClient;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @description:
 * @author: xgs
 * @date: 2020/2/11 11:56
 */
@Component
@ServerEndpoint("/websocket/{userId}")
//此注解相当于设置访问URL
public class WebSocket {
    private static final Logger logger= LoggerFactory.getLogger(WebSocket.class);

    private Session session;

    private static CopyOnWriteArraySet<WebSocket> webSockets =new CopyOnWriteArraySet<>();
    private static Map<String,Session> sessionPool = new HashMap<String,Session>();


    /**
     * 开启连接
     * @param session
     * @param userId
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value="userId")String userId) {
        logger.info("开启连接userId:{}",userId);
        this.session = session;
        //userID为空不连接
        if(StringUtils.isBlank(userId)){
            return;
        }
        if(sessionPool.get(userId)!=null){
            logger.info("此用户已存在:{}",userId);
            sessionPool.remove(userId);
        }
        webSockets.add(this);
        sessionPool.put(userId, session);
        logger.info("【websocket消息】有新的连接,总数为:{}",webSockets.size());
    }

    /**
     * 关闭连接
     */
    @OnClose
    public void onClose() {
        webSockets.remove(this);
        logger.info("【websocket消息】连接断开,总数为:{} this:{}",webSockets.size(),this);
    }

    /**
     * 接收消息
     * @param message
     */
    @OnMessage
    public void onMessage(String message) {
        logger.info("【websocket消息】收到客户端消息 message:{}",message);
    }

    /**
     * 异常处理
     * @param throwable
     */
    @OnError
    public void one rror(Throwable throwable) {
        throwable.printStackTrace();
    }



    // 此为广播消息
    public void sendAllMessage(String string) {
        for(WebSocket webSocket : webSockets) {
           // logger.info("【websocket消息】广播消息:{}",string);
            try {
                webSocket.session.getAsyncRemote().sendText(string);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 此为单点消息
    public void sendOneMessage(String userId, String message) {
        Session session = sessionPool.get(userId);
        if (session != null) {
            try {
                session.getAsyncRemote().sendText(message);
                logger.info("【websocket消息】发送消息userId:{} message{}",userId,message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

4、使用场景:直接注入自己定义的 WebSocket ,用广播还是单点,自己直接用就行了;

5、注意点:

如果用了权限框架,记得加白名单  
		eg:  如果用的是springSecurity  需要在自定义的 SecurityConfig类中 antMatchers中加上 "/websocket/**";

如果用了nginx,还需要在nginx中加上配置;

location /xx_websocket {
             proxy_pass http://localhost:9106/接口前缀/websocket;
             proxy_http_version 1.1;
             proxy_set_header Upgrade $http_upgrade;
             proxy_set_header Connection "upgrade";
      }

二、前端代码

注意:由于没有前端开发来写前端,前端代码可能会显得比较粗暴,但是能用;

前端用的是vue,废话不多说,接着上代码;

data() {
    return {  
      websock: "", //webSocket使用
      isConnect: false, //webSocket连接标识 避免重复连接
      reConnectNum: 1, //断开后重新连接的次数 免得后台挂了,前端一直重连
    };
  },

  watch: {
   //监听用户信息,当登录了就有了这个用户ID,一开始他是空的
    "$store.getters.userId": function (newValue) {
      if (newValue) {
        //登录后有值了就去创建WebSocket连接
        if (newValue != null && newValue != "") {
          console.log("userId有值了,去连webSocket");
          this.initWebSocket();
          return;
        }
      }
    },
    //监听当前路由地址  this.$route.path https://blog.csdn.net/start_sea/article/details/122499868
    "$route.path": function (newValue) {
      if (newValue) {
        //曲线救国,指定一个路由名字,当点到这个路由的时候,如果webSocket没有连接,则主动去给他连接一次
        if (newValue == "给一个路由名") {
          if (!this.isConnect) {
            this.reConnectNum = 1;
            this.initWebSocket();
          }
        }
      }
    },
  },

  methods:{
    /*webSocket start*/
    initWebSocket() {
      console.log("进入initWebSocket");
      let userId = this.$store.getters.userId;
      console.log("系统用户ID:" + userId);
      if (userId != null && userId != "") {
        // WebSocket与普通的请求所用协议有所不同,ws等同于http,wss等同于https

        //本地环境
       // let wsServer =
          `${
            location.protocol === "https" ? "wss" : "ws"
          }://localhost:9106/接口前缀/websocket/` + userId;

        //线上环境
        //webSocket 前面加一个前缀xxx_websocket_ 区分后面其他项目的webSocket
        let wsServer = "wss://域名地址或ip加端口/ nginx配置的  xxx_websocket/"+ userId;

        console.log("wsServer:", wsServer);
        this.websock = new WebSocket(wsServer);
        this.websock.onopen = this.websocketonopen;
        this.websock.onerror = this.websocketonerror;
        this.websock.onmessage = this.websocketonmessage;
        this.websock.onclose = this.websocketclose;
      }
    },
    websocketonopen() {
      console.log("WebSocket连接成功");
      //连接建立后修改标识
      this.isConnect = true;
    },
    websocketonerror(e) {
      console.log("WebSocket连接发生错误");
      //连接断开后修改标识
      this.isConnect = false;
      //连接错误 需要重连
      this.reConnect();
    },

    //接收后端推送过来的消息
    websocketonmessage(e) {
      //console.log(e)
      console.log("接收到后端传递过来的消息", e.data);
      if (e != null) {
        let str = JSON.parse(e.data);
         //todo 拿到消息了想干嘛就干嘛
      }
    },
    websocketclose(e) {
      //console.log("webSocket连接关闭:connection closed (" + e.code + ")");
      console.log("webSocket连接关闭");
      //连接断开后修改标识
      this.isConnect = false;
      this.websock='';
      this.reConnect();
    },

    reConnect() {
      console.log("尝试重新连接,本次重连次数:" + this.reConnectNum);
      if (this.reConnectNum > 6) {
        console.log("重连超过6次不再重连");
        return false;
      }
      //如果已经连上就不再重试了
      if (this.isConnect) return;
      this.initWebSocket();
      this.reConnectNum = this.reConnectNum + 1;
    },

  
    /*webSocket end*/
  
}

标签:vue,websocket,log,springCloud,userId,import,webSocket,连接
From: https://blog.51cto.com/u_10956218/6164084

相关文章

  • Vue3学习笔记(7.0)
    Vue3计算属性计算属性关键词:computed计算属性在处理一些复杂逻辑时是很有用的。可以看下以下反转字符的例子:<!--*@Author:[email protected]*@Date:2023-03-3008:30:35*@LastEditors:Mei*@LastEditTime:2023-03-3008:33:36*@FilePath:\vscode\vue_co......
  • Vue3学习笔记(4.0)
    vue.js为两个最为常用的指令提供了特别的缩写://全称<av-bind:href="url"></a>//缩写<a:href="url"></a>v-on缩写//全称<av-on:click="doSomething"></a>//缩写<a@click="doSonthing"></a>条件判断条件判断使......
  • vue之表单处理
    vue之表单处理(一)实验介绍基本用法文本多行文本单选按钮复选框多个复选框选择框实验介绍在日常的开发中,表单随处都被使用到,如:登录,问题反馈功能等。对表单的数据收集和绑定也是很常规的工作。在一般开发中处理表单,需要通过操作DOM来实现,是一个相对繁琐且低效率的工作......
  • 使用vue四种方法写一个计算器
    第一种:使用computed计算属性1.创建项目,引入vue<scripttype="text/javascript"src="js/vue.js"></script>2.实例化vue<divid="app"></div><script>varvm=newVue({el:"#app",//通过el与di......
  • VueRouter中的滚动行为
    参考:https://github.com/vuejs/vue-router/blob/dev/docs/zh/guide/advanced/scroll-behavior.md滚动行为观看VueSchool的如何控制滚动行为的免费视频课程(英文)使用前端路由,当切换到新路由时,想要页面滚到顶部,或者是保持原先的滚动位置,就像重新加载页面那样。vue-router......
  • Vue选项-实例生命周期
    Vue选项-实例生命周期VUE家族系列:Vue快速上门(1)-基础知识Vue快速上门(2)-模板语法Vue快速上门(3)-组件与复用01、基本概念1.1、先了解下MVVMVUE是基于MVVM思想实现的,❓那什么是MVVM呢?—— MVVM,是Model-View-ViewModel的缩写,是一种软件架构模式。其核心思想就是分离视图......
  • vue3面包屑导航栏
    import{useRoute,useRouter}from"vue-router";import{computed,ref,watch,watchEffect,nextTick}from"vue";constrouter=useRouter()constroute=useRoute()constbreadcrumb=ref([])/***@Date:2023-03-2817:55:20*@descript......
  • Vue——node-ops.ts
    前言node-ops.ts位于src/platforms/web/runtime/node-ops.ts,主要封装了DOM操作的API;内容importVNodefrom'core/vdom/vnode'import{namespaceMap}from'web/util/index'//创建一个由标签名称tagName指定的HTML元素//https://developer.mozilla.org/zh-CN/do......
  • vue3+elementPlus 深色主题切换
    首先安装需要的两个依赖npmi@vueuse/corenpminstallelement-plus--save在main.js中引入css文件,自定义深色背景颜色可以看ElementPlus官方网站//引入elementUIimportElementPlusfrom'element-plus'importzhCnfrom'element-plus/dist/locale/zh-cn.mjs'//引入......
  • SpringCloud之openFeign
    FeignOpenFeign是Netflix开发的声明式、模板化的HTTP请求客户端。可以更加便捷、优雅地调用httpapi。OpenFeign会根据带有注解的函数信息构建出网络请求的模板,在发送网络请求之前,OpenFeign会将函数的参数值设置到这些请求模板中。feign主要是构建微服务消费端。只要使用OpenF......