websocket实现页面数据实时加载(Springboot+vue)

在这里先提供两种思路。要实现页面数据的实时加载有两种方式,第一种是长轮询的方式。要么是后台长轮询,检测到数据变化时,通知websocket你该更新一下数据了。要么是前台长轮询,每隔一段时间发起请求获取数据。结合前后台长轮询的方式,这里想给各位推荐第二种--手动通知。我不频繁发起请求,我只在当我后台数据发上变化时,我通知websocket你该更新一下数据了。

在这篇文章中,前台长轮询的方式是最不建议的。所以不予以介绍。在这里只介绍后台长轮询和手动通知的方式。

一、引入websocket依赖。

<dependency>

   <groupId>org.springframework</groupId>

   <artifactId>spring-websocket</artifactId>

   <version>5.0.2.RELEAS</version>

</dependency>

二、添加websocket配置

三、后台websocket

1. 后台长轮询

后台不建议采用多线程方式。因为每次,比如5秒就打开一个线程专门来查看数据库,判断有无变化数据,将会大大占用服务器资源。可使用心跳服务的方式,每隔一段时间就查询一次。

首先添加一个websock。

onOpen是新的客户端连接进来调用的方法。

onMessage是接收客户端发来信息调用的方法。

sendMessage是发送信息调用的方法。

onClose是关闭websocket调用的方法。

onError是websocket发生错误调用的方法。

以下是代码。

import org.springframework.stereotype.Component;

 

import javax.websocket.*;

import javax.websocket.server.ServerEndpoint;

import java.io.IOException;

import java.util.concurrent.CopyOnWriteArraySet;

 

/**

 * socket连接

 */

@Component

@ServerEndpoint(value = "/Jqcase")

public class JqWebSocket {

 

 

    private Session session = null;

    private Integer linkCount=0;

 

    private static CopyOnWriteArraySet<JqWebSocket> webSocketSet=new CopyOnWriteArraySet<JqWebSocket>();

    /**

     * 新的客户端连接调用的方法

     * @param session

     */

    @OnOpen

    public void onOpen(Session session) throws IOException {

        System.out.println("-------------有新的客户端连接----------");

        linkCount++;

        this.session = session;

        webSocketSet.add(this);

    }

 

    /**

     * 收到客户端消息后调用的方法

     * @param message

     */

    @OnMessage

    public void onMessage(String message){

        System.out.println("发生变化"+message);

        try{

            sendMessage("发生变化"+message);

        }catch (Exception e){

            e.printStackTrace();

        }

    }

 

    /**

     * 发送信息调用的方法

     * @param message

     * @throws IOException

     */

    public static void sendMessage(String message) throws IOException {

        for (JqWebSocket item : webSocketSet) {

            item.session.getBasicRemote().sendText(message);

        }

    }

 

    @OnClose

    public void onClose(){

        //thread1.stopMe();

        linkCount--;

        webSocketSet.remove(this);

    }

 

    @OnError

    public void onError(Session session,Throwable error){

        System.out.println("发生错误");

        error.printStackTrace();

    }

}

然后就是一个心跳微服务啦。

先要在启动类开启心跳服务支持。

最后,通知websocket。

这里实现的思路是,当查询回来的数据,第一条数据的编号发生改变,就通知websocket发生改变。在上面的websocket可能会有空指针异常,所以需要获取上下文。配置上下文方法见下:

import org.springframework.beans.BeansException;

import org.springframework.context.ApplicationContext;

import org.springframework.context.ApplicationContextAware;

 

public class FrameSpringBeanUtil implements ApplicationContextAware {

 

    private static ApplicationContext applicationContext;

 

    @Override

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        this.applicationContext = applicationContext;

    }

 

    @SuppressWarnings("unchecked")

    public static <T> T getBean(String name){

        return (T) applicationContext.getBean(name);

    }

 

    public static <T> T getBean(Class<T> cls){

        return applicationContext.getBean(cls);

    }

 

}

2.后台手动通知。

当执行添加删除操作时,手动通知刷新。

四、前台websocket

注意:要对应后台的@ServerEndpoint(value = "/hesocket")

onmessage是websocket接收到信息执行的操作,在那里操作重新获取数据加载即可。

 

 

initHESocket(){

          const wsuri = "ws://68.34.21.148:9998/hczz/hesocket";

          this.websock= new WebSocket(wsuri);

          //console.log("我连接事件处置websocket了");

          this.websock.onmessage = this.heonmessage;

          this.websock.onopen = this.heonopen;

          this.websock.send = this.hesend;

          this.websock.onclose = this.heclose;

          //console.log(this.websock);

 

      },

      heonopen(){

        //连接建立之后执行send方法发送数据

        //let actions = {"test":"12345"};

        //this.websocketsend(JSON.stringify(actions));

      },

      heonmessage(e){

        //console.log("在这里执行处置事件刷新操作,谢谢!!")

        // console.log(e)

        this.getpendingEvents();

        this.gethandingEvents();

      },

      hesend(data){

        //数据发送

        this.websock.send(data);

      },

      heclose(){

        console.log("断开websocket");

        this.initHESocket();

      },

 

写得比较粗糙,有写得错误的或者有更好方法,欢迎评论、联系交流。

代码在https://download.csdn.net/download/linbyte/10874327 仅作为学习交流用途,禁止用于任何商业用途。

联系QQ:694335719

微信:lin69335719(请标明添加好友原因)

猜你喜欢

转载自blog.csdn.net/linbyte/article/details/85245229