Springboot集成WebSocket+Thymeleaf+Echarts完成数据的实时推送

完成效果图:

Springboot集成WebSocket+Thymeleaf+Echarts完成数据的实时推送_第1张图片

项目准备提要:



    com.github.pagehelper
    pagehelper-spring-boot-starter
    1.2.5



    org.springframework.boot
    spring-boot-devtools
    true



    org.apache.commons
    commons-lang3



    com.google.guava
    guava
    28.0-jre



    org.springframework.boot
    spring-boot-starter-thymeleaf



    org.springframework.boot
    spring-boot-starter-websocket

WebSocket配置

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

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

}
package com.lazyknow.websocket;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.annotation.PostConstruct;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.lazyknow.entity.user.User;
import com.lazyknow.service.user.UserService;
import com.lazyknow.vo.UserVo;

@ServerEndpoint(value = "/socket/{cmd}/{id}")
@Component
public class WebSocketHandler {

    public static Logger logger = LoggerFactory.getLogger(WebSocketHandler.class);
    
    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet webSocketSet = new CopyOnWriteArraySet();
    private String uid = "";
    private Session session;
    // 用于查询用户信息
    @Autowired
    private UserService userService;
    private static UserService userServiceMapper;

    @PostConstruct
    public void init(){
        WebSocketHandler.userServiceMapper = this.userService;
    }

    /**
     * 开启WebSocket请求
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("cmd") String cmd,@PathParam("id") String id) throws Exception {
        this.session = session;
        webSocketSet.add(this);
        uid = id;
        // 可以根据不同类型在选择执行的SQL
        if("user".equals(cmd)) {
        	List skirt = Lists.newArrayList();
        	List nums = Lists.newArrayList();
        	// 查询前10页数据
            for (int i = 0; i < 10; i++) {
            	PageInfo user = userServiceMapper.findUserInfo(i, 20);
            	List list = user.getList();
            	for (User info : list) {
            		skirt.add(info.getId()+"");
            		nums.add(info.getAge());
            		UserVo vo = new UserVo();
                	vo.setSkirt(skirt);
                	vo.setNumber(nums);
                	Thread.sleep(300);
                    this.sendMessage(JSON.toJSONString(vo));
				}
    		}
        }else {
        	this.onClose();
        }
    }
    
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
    	logger.info("参数信息:{},uid:{}",message,uid);
        //群发消息
        for (WebSocketHandler item : webSocketSet) {
            try {
            	item.sendMessage(JSON.toJSONString(message));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    	
    }

    @OnClose
    public void onClose(){
    	webSocketSet.remove(this);
        if (session != null){
            try {
                session.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    /**
     * 自定义消息推送、可群发、单发
     * */
    public static void sendInfo(String message,@PathParam("id") String id) throws IOException {
    	logger.info("推送消息到前端:{},推送信息:{}",id,message);
        for (WebSocketHandler item : webSocketSet) {
            try {
            	//这里可以设定只推送给这个id的,为null则全部推送
            	if(id==null) {
            		item.sendMessage(message);
            	}else if(item.uid.equals(id)){
            		item.sendMessage(message);
            	}
            } catch (IOException e) {
                continue;
            }
        }
    }


    @OnError
    public void onError(Session session, Throwable error) {
    	logger.error("连接异常!");
        error.printStackTrace();
    }
    
    // 发送信息
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }
    

}

前端页面




    页面展示
    







	
    

还有一些Springboot和thymeleaf的常规配置,这里就不全部写下了。

你可能感兴趣的:(Java文档)