使用WebScoket实现前端实时获取后端SpringBoot数据

WebScoket特点

服务器可以主动向客户端推送信息,客户端也可以主动向服务器发送信息,实现真正的双向平等对话。

前端JS

var webSocket;
webSocket = new WebSocket("ws://localhost:8081/LogManagement/home");
webSocket.onerror = function (event) {
	alert("连接失败");
	alert(event.data );
}
webSocket.onopen = function (event) {
    alert('连接成功');
}
webSocket.onmessage = function (event) {
	//后端传来的是JSON字符串,前端转为json
	var data = JSON.parse(event.data);
	setDisplayNum(data.ERRORToday,data.INFOToday,data.DEBUGToday,data.WARNToday);
 }

后端Java

创建WebScoketServer类

@ServerEndpoint(value = "/home")
@Component
public class WebSocketServer {

    @Autowired
    LogController logController;
    //用来记录当前在线连接数,线程安全。
    private static int onlineCount = 0;

    //线程安全Set,存放每个客户端的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

    //与某个客户端的连接会话
    private Session session;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        System.out.println(session.getAsyncRemote());
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        sendMessage("有新连接加入!当前在线人数为" + getOnlineCount());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        sendMessage("有用户退出!当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("来自客户端的消息:" + message);
        //群发消息
        sendInfo("服务端返回:" + session.getId() + "-" + message);
    }

    /**
     * 发生错误时调用
     *
     * @OnError
     **/
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }

    /**
     * 向客户端发送消息
     *
     * @param message 消息内容
     */
    private void sendMessage(String message) {
        this.session.getAsyncRemote().sendText(message);
    }

    private void sendMessage2(Map<String,Object> map) {
        this.session.getAsyncRemote().sendObject(map);
    }


    /**
     * 群发自定义消息
     */
    public void sendInfo(String message) {
        try {
            for (WebSocketServer item : webSocketSet) {
                item.sendMessage(message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}

使用定时器获取数据,群发给前端

@Scheduled(fixedDelay = 1000 * 2)
public Map<String, Object> getData() {
    String indexName = "log_log";
    Map<String, Object> map = logService.getLogStatistic(indexName);
    webSocketServer.sendInfo(JSON.toJSONString(map));
    return map;
}

开启SpringBoot定时器

在启动类加注解: @EnableScheduling
在需要定时的方法加注解: @Scheduled(fixedDelay = 1000 * 2) 表示2秒

pom中加入webscoket依赖

 <!-- WebSocket -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
    <version>2.0.4.RELEASE</version>
</dependency>
  • 2
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值