Websocket结合Stomp在vue中使用

项目中需要进行数据的实时推送, 所以采用了websocket+stomp的形式来做,增加断线重连机制,初始化连接后,可以在任意页面使用

1.安装依赖
yarn add stompjs
yarn add sockjs-client
2、新建store/modules/websocket.js
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
import { pimessagepush } from '@/api/user.js'
const state = {
  url: '',
  checkInterval: null, // 断线重连时 检测连接是否建立成功
  websocket: null,
  stompClient: null,
  listenerList: [] // 监听器列表,断线重连时 用于重新注册监听
}
const mutations = {
  WEBSOCKET_INIT(state, url) {
    if (state.stompClient == null || !state.stompClient.connected) {
      state.url = url
      if (state.stompClient != null && state.websocket.readyState === SockJS.OPEN) {
        state.stompClient.disconnect(() => {
          this.commit('WEBSOCKET_CONNECT')
        })
      } else if (state.stompClient != null && state.websocket.readyState === SockJS.CONNECTING) {
        console.log('连接正在建立')
        return
      } else {
        this.commit('WEBSOCKET_CONNECT')
      }
      if (!state.checkInterval) {
        const interval = setInterval(() => {
          console.log('检测连接:' + state.websocket.readyState)
          if (state.stompClient != null && state.stompClient.connected) {
            clearInterval(state.checkInterval)
            state.checkInterval = null
            console.log('重连成功')
          } else if (state.stompClient != null && state.websocket.readyState !== SockJS.CONNECTING) {
            // websocket的状态为open 但是stompClient的状态却是未连接状态,故此处需要把连接断掉 然后重连
            state.stompClient.disconnect(() => {
              this.commit('WEBSOCKET_CONNECT')
            })
          }
        }, 2000)
        state.checkInterval = interval
      }
    } else {
      console.log('连接已建立成功,不再执行')
    }
  },
  WEBSOCKET_CONNECT(state) {
    const _this = this
    const websock = new SockJS(state.url)
    state.websocket = websock
    // 获取STOMP子协议的客户端对象
    const stompClient = Stomp.over(websock)
    stompClient.debug = null // 关闭控制台打印
    stompClient.heartbeat.outgoing = 20000
    stompClient.heartbeat.incoming = 0// 客户端不从服务端接收心跳包
    // 向服务器发起websocket连接
    stompClient.connect(
      { name: 'test' }, // 此处注意更换自己的用户名,最好以参数形式带入
      frame => {
        console.log('链接成功!')
        state.listenerList.forEach(item => {
          state.stompClient.subscribe(item.topic, item.callback)
        })
        // unsubscribe()可以用来取消客户端对这个目的地destination的订阅
        // stompClient.subscribe("/user/queue/message", msg => {
        //   // this.getData(msg);
        //   console.log(msg)
        // });
      },
      () => { // 第一次连接失败和连接后断开连接都会调用这个函数 此处调用重连
        setTimeout(() => {
          _this.commit('WEBSOCKET_INIT', state.url)
        }, 1000)
      }
    )
    state.stompClient = stompClient
  },
  WEBSOCKET_SEND(state, p) {
    console.log('发送信息', p)
    state.stompClient.send(p.topic, {}, p.data)
  },
  WEBSOCKET_UNSUBSRCIBE(state, p) {
    state.stompClient.unsubscribe(p)
    for (let i = 0; i < state.listenerList.length; i++) {
      if (state.listenerList[i].topic === p) {
        state.listenerList.splice(i, 1)
        console.log('解除订阅:' + p + ' size:' + state.listenerList.length)
        break
      }
    }
  }
}
const actions = {
  WEBSOCKET_INIT({ commit }, url) {
    commit('WEBSOCKET_INIT', url)
  },
  WEBSOCKET_SEND({ commit }, p) {
    commit('WEBSOCKET_SEND', p)
  },
  WEBSOCKET_UNSUBSRCIBE({ commit }, p) {
    commit('WEBSOCKET_UNSUBSRCIBE', p)
  },
  // 接口形式推送消息
  PUSH_CODE({ commit }, { subjectIcfRecordId, code }) {
    const params = {
      subjectIcfRecordId: subjectIcfRecordId,
      code: code
    }
    console.log('store推送消息', params)
    pimessagepush(params)
  }
}
export default {
  state,
  mutations,
  actions
}
3、store/getters.js
const getters = {
  stompClient: state => state.websocket.stompClient,
}
export default getters
4、新建mixin/mixin_websocket.js 以便全局使用

websocket 链接的地址、接收、取消消息的地址更换实际的

export const mixins = {
  computed: {
    global_uuid() {
      const subjectIcfRecordId = this.$store.getters.subjectIcfRecordId
      const subjectId = this.$store.getters.subjectId
      return `${subjectIcfRecordId}-1-${subjectId}`
    }
  },
  methods: {
    // websocket建立链接
    global_websocket_connect() {
      const baseUrl = this.$baseApi
      const wsUrl = `${baseUrl}/oceanus-socket/server-ws`
      this.$store.dispatch('WEBSOCKET_INIT', wsUrl) // 建立链接
    },
    // 发送消息
    global_websocket_send_message(code) {
      const params = {
        subjectIcfRecordId: this.$store.getters.subjectIcfRecordId,
        code: code
      }
      this.$store.dispatch('PUSH_CODE', params)
    },
    // 接收订阅消息
    global_websocket_receive_message() {
      const stompClient = this.$store.getters.stompClient
      const interval = setInterval(() => { // 增改轮询解决刷新问题
        if (stompClient != null && stompClient.connected) {
          clearInterval(interval)
          stompClient.subscribe(`/topic/${this.global_uuid}/messages`, res => {
            const result = JSON.parse(res.body)
            console.log('接收消息', result)
            if (result.data === '2203' || result.data === '2106') { // 电子签名按钮可以显示
              this.$store.commit('SET_SHOW_SIGN_BTN', true)
            }
            if (result.data === '2101') { // 知情同意悬浮按钮显示
              this.$store.commit('SET_SHOW_READ_BTN', true)
              this.toRead()
            }
          })
        } else {
          console.log('等待连接中')
        }
      }, 1000)
    },
    // 取消订阅消息
    global_websocket_unsubscribe() {
      const stompClient = this.$store.getters.stompClient
      if (stompClient != null && stompClient.connected) {
        this.$store.dispatch('WEBSOCKET_UNSUBSRCIBE', `/topic/${this.global_uuid}/messages`)
      }
    },
    // 获取url参数方法
    global_getQueryString(name) {
      var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
      var r = window.location.search.substr(1).match(reg)
      if (r != null) return unescape(r[2])
      return null
    }
  }
}
5、将mixin设置为全局
import { mixins } from './mixin/mixin_websocket'
Vue.mixin(mixins)

这样就配置好了,接下来就可以在使用的页面调用了,本项目发送消息是通过掉后端接口形式

//test.vue
 created() {
    this.global_websocket_connect() // websocket建立链接
  }
  mounted(){
    const code = this.knowingType === '21' ? '2101' : '2205'
    this.global_websocket_send_message(code) // 发送消息 开始阅读中
    this.global_websocket_receive_message() // 接收消息
  }

你可能感兴趣的:(Websocket结合Stomp在vue中使用)