springBoot+定时任务+webSocket实现每三秒推送一次消息(不同页面推送不同消息)

1 springBoot中已经集成webSocket的依赖

maven坐标

	<!--webSocket使用-->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-websocket</artifactId>
			<version>5.1.5.RELEASE</version>
		</dependency>

2 建立WebSocketConfig类

package com.guoheng.hazard.config;

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

/**
 * 类功能描述: WebSocket配置类
 * 使用此配置可以关闭servlet容器对websocket端点的扫描,这个暂时没有深入研究。
 * @author fbl
 * @date 2019-12-03 08:33
 */
@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

3 建立 WebSocketServer类

package com.guoheng.hazard.manager.websocket;

import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
/**
 * 类功能描述: webSocket服务层
 * 这里我们连接webSocket的时候,路径中传一个参数值id,用来区分不同页面推送不同的数据
 *
 * @author fbl
 * @date 2019-02-13 8:02
 */
@ServerEndpoint(value = "/websocket/{id}")
@Component
public class WebSocketServer {
    /**
     * 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private static int onlineCount = 0;

    /**
     * concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
     */
    public static ConcurrentHashMap<Integer, WebSocketServer> webSocketSet = new ConcurrentHashMap<Integer, WebSocketServer>();

    /**
     * 与某个客户端的连接会话,需要通过它来给客户端发送数据
     */
    private Session session;

    /**
     * 传过来的id
     */
    private Integer id = 0;

    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(@PathParam(value = "id") Integer param, Session session) {

        //接收到发送消息的人员编号
        id = param;
        this.session = session;
        /**加入set中*/
        webSocketSet.put(param,this);
        /**在线数加1*/
        addOnlineCount();
        System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
        try {
            sendMessage("-连接已建立-");
        } catch (IOException e) {
            System.out.println("IO异常");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if (id != null && id != 0) {
            /** 从set中删除 */
            webSocketSet.remove(id);
            /** 在线数减1 */
            subOnlineCount();
            System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
        }
    }

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

        try {
            this.sendMessage(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

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


    public  void sendMessage(String message) throws IOException {
        synchronized (session) {
            getSession().getBasicRemote().sendText(message);
        }
    }

    /**
     * 给指定的人发送消息
     * @param message
     */
    public  void sendToMessageById(Integer id,String message) {
        try {
            if (webSocketSet.get(id) != null) {
                webSocketSet.get(id).sendMessage(message);
            } else {
                System.out.println("webSocketSet中没有此key,不推送消息");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

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

    public Session getSession() {
        return session;
    }

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

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

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

4 建立连接webSocket的参数枚举

记得与前端约定好,那个参数(此处是id)代表那个页面

package com.guoheng.hazard.common.enums;

import lombok.Data;

/**
 * 枚举描述: 不同页面区分webSocket
 *
 * @author fbl
 * @date 2019-12-12 09:34
 */
public enum WebSocketEnum {
    /**
     * 实时报警
     */
    SOCKET_ENUM_ALARM(1,"实时报警"),

    /**
     * 温度传感器
     */
    SOCKET_ENUM_TEMP(2,"温度传感器"),

    /**
     * 压力传感器
     */
    SOCKET_ENUM_PRESSURE(3,"压力传感器"),

    /**
     * 液位传感器
     */
    SOCKET_ENUM_LIQUID(4,"液位传感器"),

    /**
     * 可燃传感器
     */
    SOCKET_ENUM_COMBUSTIBLE(5,"可燃传感器"),

    /**
     * 有毒传感器
     */
    SOCKET_ENUM_POISONOUS(6,"有毒传感器");


    private Integer code;
    private String msg;

    WebSocketEnum(Integer code,String msg){
        this.code = code;
        this.msg = msg;
    }
    public Integer getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }
}

5 定时任务我们使用spring自带的task

这是服务层使用webSocket+定时任务的代码

   @Override
    @Scheduled(cron = "0/3 * * * * ?")
    public Result realTimeAlarm() {
        if (CollectionUtil.isNotEmpty(WebSocketServer.webSocketSet)) {
            // 查询待处理报警类
            List<MajorHazardAlarmSelectDTO> alarm = majorHazardAlarmMapper.getAlarm(null, null, null
                    , null, null, 1);
            String alarmToString = JSON.toJSONString(alarm);
            webSocketServer.sendToMessageById(SOCKET_ENUM_ALARM.getCode(), alarmToString);
        }
        return Result.success();
    }

控制层代码

  @ApiOperation(value = "实时报警")
    @GetMapping(value = "data/major/hazard/realTimeAlarm")
    public Result realTimeAlarm() {
        return safeOneMapService.realTimeAlarm();
    }

至此,调用这个接口,连接webSocket,传递不同的参数,就可以每三秒推送一次数据库中的数据,达到实时刷新的目的,同时不同页面传不同参数,达到推送不同数据的目的

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值