若依(ruoyi)使用websocket推送数据到前端

原创 小尘哥 小尘哥 2024年09月05日 21:44 河南

系统基础框架使用了若依的微服务版,接到一个需求,一个大数据量的审核任务的审核进度要在页面上实时展示出来。基于此需求迅速想到最简单粗暴的解决方式:前端定时轮询。但是仅靠前端轮询肯定是不靠谱的,因为每次请求都是一次Http,会大量消耗资源,,因此综合分析后决定使用websocket建立长连接进行数据推送的方式。

以下为简单的消息推送示例,使用时需要根据自身业务集成具体业务实现。

一、后端改造

1、pom增加websocket依赖

 
  1. <dependency>

  2. <groupId>org.springframework.boot</groupId>

  3. <artifactId>spring-boot-starter-websocket</artifactId>

  4. </dependency>

2、配置websocketconfig

 
  1. @Configuration

  2. @EnableWebSocket

  3. public class WebSocketConfig {

  4. @Bean

  5. public ServerEndpointExporter serverEndpointExporter() {

  6. return new ServerEndpointExporter();

  7. }

  8. }

3、 编写WebSocket服务类

 
  1. @Component

  2. @ServerEndpoint(value = "/system/websocket")

  3. public class WebSocket {

  4. private static Map<String , Session> clientMap = new ConcurrentHashMap<>();

  5. /**

  6. * 客户端与服务端连接成功

  7. * @param session

  8. */

  9. @OnOpen

  10. public void onOpen(Session session){

  11. clientMap.put(session.getId(),session);

  12. }

  13. /**

  14. * 客户端与服务端连接关闭

  15. * @param session

  16. */

  17. @OnClose

  18. public void onClose(Session session){

  19. clientMap.remove(session.getId());

  20. }

  21. /**

  22. * 客户端与服务端连接异常

  23. * @param error

  24. * @param session

  25. */

  26. @OnError

  27. public void onError(Throwable error,Session session) {

  28. error.printStackTrace();

  29. }

  30. /**

  31. * 客户端向服务端发送消息

  32. * @param message

  33. * @throws IOException

  34. */

  35. @OnMessage

  36. public void onMsg(Session session,String message) throws IOException {

  37. //以下为模拟发送消息

  38. sendMessage();

  39. }

  40. @Scheduled(cron = "0/10 * * * * ?")

  41. private void sendMessage(){

  42. //获得Map的Key的集合

  43. Set<String> sessionIdSet = clientMap.keySet();

  44. // 此处相当于一个广播操作//迭代Key集合

  45. for (String sessionId : sessionIdSet) {

  46. //根据Key得到value

  47. Session session = clientMap.get(sessionId);

  48. //发送消息给客户端,每10s给前端推送一个UUI

  49. session.getAsyncRemote().sendText(IdUtils.simpleUUID());

  50. }

  51. }

  52. }

二、前端改造

websocket连接工具类

 
  1. /**

  2. * 参数说明:

  3. * webSocketURL:String webSocket服务地址 eg: ws://127.0.0.1:8080/websocket (后端接口若为restful风格可以带参数)

  4. * callback:为带一个参数的回调函数

  5. * message:String 要传递的参数值(不是一个必要的参数)

  6. */

  7. export default {

  8. // 初始化webSocket

  9. webSocketInit (webSocketURL) { // ws://127.0.0.1:8080/websocket

  10. this.webSocket = new WebSocket(webSocketURL)

  11. this.webSocket.onopen = this.onOpenwellback

  12. this.webSocket.onmessage = this.onMessageCallback

  13. this.webSocket.onerror = this.onErrorCallback

  14. this.webSocket.onclose = this.onCloseCallback

  15. },

  16. // 自定义回调函数

  17. setOpenCallback (callback) { // 与服务端连接打开回调函数

  18. this.webSocket.onopen = callback

  19. },

  20. setMessageCallback (callback) { // 与服务端发送消息回调函数

  21. this.webSocket.onmessage = callback

  22. },

  23. setErrorCallback (callback) { // 与服务端连接异常回调函数

  24. this.webSocket.onerror = callback

  25. },

  26. setCloseCallback (callback) { // 与服务端连接关闭回调函数

  27. this.webSocket.onclose = callback

  28. },

  29. close () { // 关闭连接

  30. this.webSocket.close()

  31. },

  32. sendMessage (message) { // 发送消息函数

  33. this.webSocket.send(message)

  34. }

  35. }

2、示例页面

 
  1. <template>

  2. <div>

  3. <el-button type="primary" @click="sendMessage">发送消息</el-button>

  4. <el-button type="primary" @click="closeMessage">关闭消息</el-button>

  5. <p v-for="(content, index) in text">{{index}}.{{ content }}</p>

  6. </div>

  7. </template>

  8. <script>

  9. import websocket from '@/api/websocket'

  10. import request from '@/utils/request'

  11. export default {

  12. name: "WebSocketDemo",

  13. data () {

  14. return {

  15. text: [],

  16. webSocketObject: null

  17. }

  18. },

  19. created() {

  20. websocket.webSocketInit('ws://localhost:9250/system/websocket')

  21. websocket.setOpenCallback(res => {

  22. console.log('建立连接成功',res);

  23. })

  24. websocket.setMessageCallback(res => {

  25. this.text.push(res.data) ;

  26. console.log('发送消息成功',res);

  27. })

  28. websocket.setErrorCallback(res => {

  29. console.log('接收失败消息',res);

  30. })

  31. websocket.setCloseCallback(res => {

  32. console.log('连接关闭',res);

  33. })

  34. websocket.setCloseCallback(res => {

  35. console.log('连接关闭',res);

  36. })

  37. },

  38. methods: {

  39. sendMessage () {

  40. // 使用websocket交互

  41. // websocket.sendMessage("123");

  42. // 常规接口,通过http交互

  43. request({

  44. url : '/system/websocket/send?msg=123',

  45. method : 'post'

  46. }).then((res) => {

  47. this.text.push(res.data) ;

  48. console.log(this.text)

  49. })

  50. },

  51. //关闭websocket连接(若后台依然有定时任务,建议使用http的方式删除后台的定时任务执行)

  52. closeMessage(){

  53. websocket.close()

  54. }

  55. }

  56. }

  57. </script>

三、示例效果

定时推送uuid并在页面展示,可根据实际业务,修改为返回需要的审核状态即可。

图片

其他大佬推荐可以使用MQTT、comet(长轮询)、SSE(长连接)等方式实现以上需求,待有时间再做一篇各种方式的对比。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值