若依(ruoyi)使用websocket推送數(shù)據(jù)到前端

系統(tǒng)基礎(chǔ)框架使用了若依的微服務(wù)版,接到一個(gè)需求,一個(gè)大數(shù)據(jù)量的審核任務(wù)的審核進(jìn)度要在頁(yè)面上實(shí)時(shí)展示出來(lái)?;诖诵枨笱杆傧氲阶詈?jiǎn)單粗暴的解決方式:前端定時(shí)輪詢。但是僅靠前端輪詢肯定是不靠譜的,因?yàn)槊看握?qǐng)求都是一次Http,會(huì)大量消耗資源,,因此綜合分析后決定使用websocket建立長(zhǎng)連接進(jìn)行數(shù)據(jù)推送的方式。

以下為簡(jiǎn)單的消息推送示例,使用時(shí)需要根據(jù)自身業(yè)務(wù)集成具體業(yè)務(wù)實(shí)現(xiàn)。

一、后端改造

1、pom增加websocket依賴

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

2、配置websocketconfig

@Configuration
@EnableWebSocket
public class WebSocketConfig {

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

}

3、 編寫WebSocket服務(wù)類

@Component
@ServerEndpoint(value = "/system/websocket")
public class WebSocket {
    private static Map<String , Session> clientMap = new ConcurrentHashMap<>();

    /**
     * 客戶端與服務(wù)端連接成功
     * @param session
     */
    @OnOpen
    public void onOpen(Session session){
        clientMap.put(session.getId(),session);
    }

    /**
     * 客戶端與服務(wù)端連接關(guān)閉
     * @param session
     */
    @OnClose
    public void onClose(Session session){
        clientMap.remove(session.getId());
    }

    /**
     * 客戶端與服務(wù)端連接異常
     * @param error
     * @param session
     */
    @OnError
    public void onError(Throwable error,Session session) {
        error.printStackTrace();
    }

    /**
     * 客戶端向服務(wù)端發(fā)送消息
     * @param message
     * @throws IOException
     */
    @OnMessage
    public void onMsg(Session session,String message) throws IOException {
        //以下為模擬發(fā)送消息
        sendMessage();
    }

    @Scheduled(cron = "0/10 * * * * ?")
    private void sendMessage(){
        //獲得Map的Key的集合
        Set<String> sessionIdSet = clientMap.keySet();
        // 此處相當(dāng)于一個(gè)廣播操作//迭代Key集合
        for (String sessionId : sessionIdSet) {
            //根據(jù)Key得到value
            Session session = clientMap.get(sessionId);
            //發(fā)送消息給客戶端,每10s給前端推送一個(gè)UUI
            session.getAsyncRemote().sendText(IdUtils.simpleUUID());
        }
    }

}

二、前端改造

websocket連接工具類

/**
 * 參數(shù)說(shuō)明:
 *  webSocketURL:String    webSocket服務(wù)地址    eg: ws://127.0.0.1:8080/websocket (后端接口若為restful風(fēng)格可以帶參數(shù))
 *  callback:為帶一個(gè)參數(shù)的回調(diào)函數(shù)
 *  message:String 要傳遞的參數(shù)值(不是一個(gè)必要的參數(shù))
 */
export default {
  // 初始化webSocket
  webSocketInit (webSocketURL) { // ws://127.0.0.1:8080/websocket
    this.webSocket = new WebSocket(webSocketURL)
    this.webSocket.onopen = this.onOpenwellback
    this.webSocket.onmessage = this.onMessageCallback
    this.webSocket.onerror = this.onErrorCallback
    this.webSocket.onclose = this.onCloseCallback
  },

  // 自定義回調(diào)函數(shù)
  setOpenCallback (callback) { //  與服務(wù)端連接打開回調(diào)函數(shù)
    this.webSocket.onopen = callback
  },
  setMessageCallback (callback) { //  與服務(wù)端發(fā)送消息回調(diào)函數(shù)
    this.webSocket.onmessage = callback
  },
  setErrorCallback (callback) { //  與服務(wù)端連接異常回調(diào)函數(shù)
    this.webSocket.onerror = callback
  },
  setCloseCallback (callback) { //  與服務(wù)端連接關(guān)閉回調(diào)函數(shù)
    this.webSocket.onclose = callback
  },

  close () { // 關(guān)閉連接
    this.webSocket.close()
  },
  sendMessage (message) { // 發(fā)送消息函數(shù)
    this.webSocket.send(message)
  }
}

2、示例頁(yè)面

<template>
  <div>
    <el-button type="primary" @click="sendMessage">發(fā)送消息</el-button>
    <el-button type="primary" @click="closeMessage">關(guān)閉消息</el-button>
    <p v-for="(content, index) in text">{{index}}.{{ content }}</p>
  </div>
</template>
<script>
import websocket from '@/api/websocket'
import request from '@/utils/request'
export default {
  name: "WebSocketDemo",
  data () {
    return {
      text: [],
      webSocketObject: null
    }
  },
  created() {
    websocket.webSocketInit('ws://localhost:9250/system/websocket')
    websocket.setOpenCallback(res => {
      console.log('建立連接成功',res);
    })
    websocket.setMessageCallback(res => {
      this.text.push(res.data) ;
      console.log('發(fā)送消息成功',res);
    })
    websocket.setErrorCallback(res => {
      console.log('接收失敗消息',res);
    })
    websocket.setCloseCallback(res => {
      console.log('連接關(guān)閉',res);
    })
    websocket.setCloseCallback(res => {
      console.log('連接關(guān)閉',res);
    })

  },
  methods: {
    sendMessage () {
      // 使用websocket交互
      // websocket.sendMessage("123");
      // 常規(guī)接口,通過http交互
      request({
        url : '/system/websocket/send?msg=123',
        method : 'post'
      }).then((res) => {
          this.text.push(res.data) ;
          console.log(this.text)
      })
    },

//關(guān)閉websocket連接(若后臺(tái)依然有定時(shí)任務(wù),建議使用http的方式刪除后臺(tái)的定時(shí)任務(wù)執(zhí)行)
    closeMessage(){
      websocket.close()
    }
  }
}
</script>

三、示例效果

定時(shí)推送uuid并在頁(yè)面展示,可根據(jù)實(shí)際業(yè)務(wù),修改為返回需要的審核狀態(tài)即可。


image.png

其他大佬推薦可以使用MQTT、comet(長(zhǎng)輪詢)、SSE(長(zhǎng)連接)等方式實(shí)現(xiàn)以上需求,待有時(shí)間再做一篇各種方式的對(duì)比。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容