websocket实践(后台触发前端刷新)

第一步、首先需要安装组件

yarn add stompjs
yarn add sockjs-client

安装完成后,(package.json)文件出现下面代码:

第二步,前端增加代理配置

(vue.config.js)文件中

使用  ws: true, 支持websocket

第三步、后端增websocket依赖

pom.xml文件中

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

第四步、后端配置消息代理

使用spring自带的WebSocketMessageBrokerConfigurer

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.*;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // 注册消息监听端点,使用SockJS协议
        StompWebSocketEndpointRegistration registration = registry.addEndpoint("/stompPoint");
        registration.setAllowedOriginPatterns("*");
        registration.withSockJS();
    }
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        if (enable) {
            // 启用消息代理
            registry.enableStompBrokerRelay("/msgOneTopic").setRelayHost(host)
            .setRelayPort(port).setSystemHeartbeatReceiveInterval(5000)
            .setSystemHeartbeatSendInterval(5000);
        } else {
            registry.enableSimpleBroker("/topic","/retMsg");
        }
    }

}

第五步、前端连接并监听

需要注意监听的端点,和后端注册的端点一致

<template>
  <div class="websocket"></div>
</template>
<script>
  import SockJS from 'sockjs-client'
  import Stomp from 'stompjs'
  import {mapActions, mapGetters, mapMutations, mapState} from 'vuex'

  export default {
    data() {
      return {
        socketUrl: '/stompPoint',
        socket: null,
        stompClient: null,
        timer: null,
      }
    },
    mounted() {
      this.initWebSocket()
    },
    destroyed() {
      // 页面离开时断开连接,清除定时器
      this.disconnect();
      clearInterval(this.timer);
    },
    computed: {

    },
    methods: {
      initWebSocket() {
        // 建立连接对象
        this.socket = new SockJS(socketUrl)
        // 获取STOMP子协议的客户端对象
        this.stompClient = Stomp.over(this.socket)
        // 向服务器发起websocket连接
        this.stompClient.connect({}, (message) => {
          console.log("-----------------连接成功-----------------")
          console.log(message);
          // 连接成功
          this.successCallback();
        }, error => {
          console.log("-----------------连接失败-----------------")
          console.log(error)
          this.reconnect(this.socketUrl, this.successCallback)
        })
      },
      // 连接成功
      successCallback() {
        this.stompClient.subscribe('/topic/msgOneTopic', (msg) => {
          const receivedMsg = JSON.parse(msg.body)//接收服务端信息
          console.info("-------------successCallback---消息-------------");
          console.info(receivedMsg)
          //下面就可以根据从后端接收到消息干事情了
        })
      },
      reconnect(socketUrl, successCallback) {
        console.info('-----------------开始重新连接WebSocket-----------------')
        setTimeout(() => {
          this.socket = new SockJS(socketUrl)
          this.stompClient = Stomp.over(this.socket)
          this.stompClient.connect({}, (frame) => {
            console.info("-----------------重新连接WebSocket成功-----------------")
            console.info(frame);
            // 连接成功,清除定时器
            successCallback()
          }, error => {
            console.info("-----------------重新连接WebSocket成功-----------------")
            console.info(error);
            this.reconnect(socketUrl, successCallback);
          })
        }, 10000)
      },
      // 断开连接
      disconnect() {
        if (this.stompClient != null) {
          this.stompClient.disconnect()
        }
      }
    }
  }
</script>

<style lang="less" scoped>
</style>

第六步、后端发送消息


@Service("webSocketService")
public class WebSocketService {

	@Autowired
    private SimpMessagingTemplate simpMessagingTemplate;
		
	public void sendMsg() throws Exception {
        String destination = "/msgOneTopic";
        simpMessagingTemplate.convertAndSend(destination, "测试信息");
    }
}

第七步、前端增加处理逻辑

上面第五步中,successCallBack中继续增加我们需要的业务逻辑

  • 12
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用WebSocket实现数据库更新时前端页面的实时刷新,你可以按照以下步骤进行操作: 1. 在后端,使用WebSocket协议与前端建立连接。你可以使用一些流行的WebSocket库,如Socket.io(Node.js)或Tornado(Python)来简化这个过程。 2. 在前端,使用JavaScript的WebSocket API与后端建立连接。可以使用以下代码示例: ```javascript const socket = new WebSocket('ws://your-server-url'); socket.onopen = () => { console.log('WebSocket连接已建立'); }; socket.onmessage = (event) => { console.log('收到消息:', event.data); // 在收到消息时执行相应的操作,如更新页面内容 }; socket.onclose = () => { console.log('WebSocket连接已关闭'); }; ``` 3. 在后端,监听数据库的更新操作。当数据库发生更新时,通过WebSocket前端发送消息。具体实现方式取决于你使用的数据库和后端语言。 例如,如果你使用Node.js和MongoDB,可以使用MongoDB的Change Streams功能来监听数据库的变化,并通过WebSocket发送消息给前端。以下是一个简单的示例: ```javascript const { MongoClient } = require('mongodb'); const WebSocket = require('ws'); const url = 'mongodb://localhost:27017'; const dbName = 'your-database-name'; const collectionName = 'your-collection-name'; const wss = new WebSocket.Server({ port: 8080 }); (async function () { const client = await MongoClient.connect(url, { useUnifiedTopology: true }); const db = client.db(dbName); const collection = db.collection(collectionName); const changeStream = collection.watch(); changeStream.on('change', (change) => { const message = JSON.stringify(change); wss.clients.forEach((client) => { if (client.readyState === WebSocket.OPEN) { client.send(message); // 向前端发送更新消息 } }); }); })(); ``` 这样,当数据库中的数据发生变化时,后端会将变化信息通过WebSocket发送给前端前端页面可以根据接收到的消息来实时更新内容。 请注意,以上代码只是一个简单的示例,实际上,你需要根据你的具体需求和技术栈进行相应的配置和开发。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值