• websocket实时推送统计数据给前端页面


    • 前提须知:websocket基本使用

    • 业务场景,每秒推送统计数据给前端页面,分别显示前天,昨天,今天的前十名客户数据

    连接触发业务定义

    • @ServerEndpoint("/smsMCustomerStaTop10Ws")定义推送数据给到具体的连接标识
    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONArray;
    import com.alibaba.fastjson.JSONObject;
    import com.xyc.monitor.service.SmsMonitorService;
    import com.xyc.monitor.service.impl.SmsMonitorServiceImpl;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    
    import javax.websocket.*;
    import javax.websocket.server.ServerEndpoint;
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Set;
    import java.util.concurrent.ConcurrentHashMap;
    import java.util.concurrent.CopyOnWriteArraySet;
    
    /**
     * Top10客户发送量推送
     */
    @Component
    @ServerEndpoint(value = "/smsMCustomerStaTop10Ws")
    public class SmsMCustomerStaTop10Ws {
    
        private static final Logger LOGGER = LoggerFactory.getLogger(SmsMCustomerStaTop10Ws.class);
    
    
        //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
        private static int onlineCount = 0;
    
        //concurrent包的线程安全Set,用来存放每个客户端对应的当前对象。
        private static Set<SmsMCustomerStaTop10Ws> webSocketSet = new CopyOnWriteArraySet<SmsMCustomerStaTop10Ws>();
    
        private static Map<Session,Integer> map = new ConcurrentHashMap<>();
    
        //与某个客户端的连接会话,需要通过它来给客户端发送数据
        private Session session;
        //客户端传过来的参数 ,ip:port
        private String parameter;
    
        private static SmsMonitorService smsMonitorService;
    
        @Autowired
        public void setSmsMonitorService(SmsMonitorService smsMonitorService) {
            SmsMCustomerStaTop10Ws.smsMonitorService = smsMonitorService;
        }
    
        /**
         *  连接建立成功调用的方法
         * @param session
         */
        @OnOpen
        public void onOpen(Session session) {
            this.session = session;
            webSocketSet.add(this);     //加入set中
            addOnlineCount();           //在线数加1
            LOGGER.info("SmsMCustomerStaTop10Ws ===> 有新连接加入!当前在线人数为" + getOnlineCount());
        }
    
        /**
         * 连接关闭调用的方法
         */
        @OnClose
        public void onClose() {
    
            map.remove(this.session);
            //UDPMsgQueueStatusClient.removeUdpClient(parameter);
            webSocketSet.remove(this);  //从set中删除
            subOnlineCount();           //在线数减1
            LOGGER.info("SmsMCustomerStaTop10Ws ===> 有一连接关闭!当前在线人数为" + getOnlineCount());
        }
    
        /**
         * 收到客户端消息后调用的方法
         *
         * @param message 客户端发送过来的消息
         *
         * */
        @OnMessage
        public void onMessage(String message, Session session) {
            //关闭前一个udp
            //UDPMsgQueueStatusClient.removeUdpClient(parameter);
            //this.parameter = message;
            JSONArray objects = JSON.parseArray(message);
            //JSONObject jso = JSON.parseObject(message);
            Integer status= objects.getJSONObject(0).getInteger("status");
            //SmsMonitorServiceImpl.statusSCSSo = status;
            map.put(session,status);
            LOGGER.info("SmsMCustomerStaTop10Ws ===> 来自客户端的消息:" + message);
        }
    
        /**
         * 发生错误时调用
         */
        @OnError
        public void onError(Session session, Throwable error) {
            LOGGER.info("SmsMCustomerStaTop10Ws 发生错误");
            LOGGER.error("onError ===> ", error);
        }
    
        /**
         * 推送触发
         */
        private static void pushTrigger() {
            if(SmsMCustomerStaTop10Ws.onlineCount >= 1) {
                if(!SmsMonitorServiceImpl.isPushSCS)
                    SmsMonitorServiceImpl.isPushSCS = true;
                smsMonitorService.pushSmsMCustomerStaTop10();
    
            }
            if(SmsMCustomerStaTop10Ws.onlineCount == 0) {
                SmsMonitorServiceImpl.isPushSCS = false;
            }
        }
    
        /**
         *  发送文本类型消息  192.168.3.146:10086
         * @throws IOException
         */
        public static void sendInfo(Integer status,Object obj) throws IOException {
            for (SmsMCustomerStaTop10Ws item : webSocketSet) {
                try {
                    Session session = item.session;
                    Integer integer = map.get(session);
                    if(integer == status){
                        item.session.getBasicRemote().sendText(JSON.toJSONString(obj));
                    }else{
                        continue;
                    }
                } catch (Exception e) {
                    LOGGER.info("SmsMCustomerStaTop10Ws ===> 发送文本消息错误", e);
                }
            }
        }
    
        public static synchronized int getOnlineCount() {
            return onlineCount;
        }
    
        public static synchronized void addOnlineCount() {
            SmsMCustomerStaTop10Ws.onlineCount++;
            pushTrigger();
        }
    
        public static synchronized void subOnlineCount() {
            SmsMCustomerStaTop10Ws.onlineCount--;
            pushTrigger();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151

    使用到的业务方法

    • 以上onOpen()方法最终触发的业务方法smsMonitorService.pushSmsMCustomerStaTop10();
    
    /**
         * 记录线程数,保证只创建一个线程
         */
        private volatile static int threadCountSCS = 0;
      /**
         * 数据推送开关,是否推送数据到前端,默认关闭
         */
        public static boolean isPushSCS = false;
          /**
         * 今日1,昨天2,前天3 数据 默认今日
         */
         
        private static ImmutableSet<Integer> statusSCS = ImmutableSet.of(1, 2, 3);
        
     @Override
        public void pushSmsMCustomerStaTop10() {
            if (threadCountSCS >= 1)
                return;
                
          threadCountSCS++;
          
            new Thread() {
                public void run() {
                  
                    Thread.currentThread().setName("pushSmsMCustomerStaTop10-" + threadCountSCS);
                    System.out.println("top10客户发送量推送服务线程启动");
                    while (isPushSCS) {
                        for (Integer statusSC : statusSCS) {
                            try {
                                List<SmsMCustomerStaVo> smsMCustomerStaTop10 = smsMonitorMapper.findSmsMCustomerStaTop10(statusSC);
                                List<SmsMCustomerStaView> smsMCustomerStaViewList = new ArrayList<>();
                                int i = 1;
                                for (SmsMCustomerStaVo sm : smsMCustomerStaTop10) {
                                    SmsMCustomerStaView smsMCustomerStaView = new SmsMCustomerStaView();
                                    smsMCustomerStaView.setId(i);
                                    smsMCustomerStaView.setShortName(SmsSymbol.customerMap.get(sm.getCustomerNo()).getShortName());
                                    smsMCustomerStaView.setCustomerName(SmsSymbol.customerMap.get(sm.getCustomerNo()).getName());
                                    smsMCustomerStaView.setSubmitCount(sm.getAllCount());
                                    Integer issueCount = sm.getSendSuccessCount() + sm.getSendFailCount() + sm.getSubmitSuccessCount(); //下发总量 = 总量除开提交失败
                                    smsMCustomerStaView.setIssueCount(issueCount);
                                    //成功率(前30分钟成功率)
                                    Double sendSuccessCountRate = 0D;
                                    if(sm != null && sm.getAllCountThirty() != null &&  sm.getAllCountThirty() != 0){
                                        sendSuccessCountRate = sm.getSendSuccessCountThirty() / sm.getAllCountThirty().doubleValue();
                                    }
                                    //未知率
                                    Double unknownRateRate = 0D;
                                    if(sm != null && sm.getAllCount() != null && sm.getAllCount() != 0){
                                        //sendSuccessCountRate = sm.getSendSuccessCount() / issueCount.doubleValue(); //发送成功率
                                        unknownRateRate = sm.getSubmitSuccessCount() / sm.getAllCount().doubleValue(); //未知率 = 提交成功 / 提交总量
                                    }
                                    smsMCustomerStaView.setSuccessRate(sendSuccessCountRate == 0 ?"0%":new DecimalFormat("#0.00").format(sendSuccessCountRate * 100) + "%");
                                    smsMCustomerStaView.setUnknownRate(unknownRateRate == 0 ?"0%":new DecimalFormat("#0.00").format(unknownRateRate * 100) + "%");
                                    i++;
                                    smsMCustomerStaViewList.add(smsMCustomerStaView);
                                }
                                //List collect = smsMCustomerStaViewList.stream().sorted(Comparator.comparing(SmsMCustomerStaView::getSubmitCount).reversed()).collect(Collectors.toList());
                                SmsMCustomerStaTop10Ws.sendInfo(statusSC,smsMCustomerStaViewList);
    
                            } catch (Exception e) {
                                // TODO Auto-generated catch block
                                log.error("top10客户发送量推送服务报错",e );
                            }
                        }
                        try {
                          Thread.sleep(1000);
                        }catch (Exception e){
                            System.out.println(e);
                        }
                    }
                    System.out.println("top10客户发送量推送服务线程停止");
                    threadCountSCS--;
                }
            }.start();
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76

    涉及的查询sql

    • 以上smsMonitorMapper.findSmsMCustomerStaTop10(statusSC);(传参区分查 前日/昨日/今日 数据)
    • oracle数据库查询语句
    <select id="findSmsMCustomerStaTop10" resultMap="SmsMCustomerStaResultMap">
    		select t.* from (
    		 SELECT SUM(ALL_COUNT) ALL_COUNT,SUM(SUBMIT_SUCCESS_COUNT) SUBMIT_SUCCESS_COUNT,SUM(SUBMIT_FAIL_COUNT) SUBMIT_FAIL_COUNT,
    		 SUM(SEND_SUCCESS_COUNT) SEND_SUCCESS_COUNT,SUM(SEND_FAIL_COUNT) SEND_FAIL_COUNT,SUM(ALL_COUNT_THIRTY) ALL_COUNT_THIRTY,
    		SUM(SEND_SUCCESS_COUNT_THIRTY) SEND_SUCCESS_COUNT_THIRTY,CUSTOMER_NO
    		 FROM SMS_M_CUSTOMER_STA
    		 <if test="statusSCS == 1">
    			 WHERE STA_DATE_TIME >= trunc(sysdate)
    		 if>
    		<if test="statusSCS == 2">
    			WHERE STA_DATE_TIME >= trunc(sysdate-1) AND STA_DATE_TIME  trunc(sysdate)
    		if>
    		<if test="statusSCS == 3">
    			WHERE STA_DATE_TIME >= trunc(sysdate-2) AND STA_DATE_TIME  trunc(sysdate-1)
    		if>
    	    GROUP BY CUSTOMER_NO ORDER BY ALL_COUNT DESC)t where rownum <= 20
    	select>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    推送数据给前端演示图

    在这里插入图片描述

  • 相关阅读:
    计算机毕业设计:基于HTML学校后台用户登录界面模板源码
    Mac 安装php多版本,brew安装php8.0
    SystemVerilog Randomization点点滴滴
    MySQL的Undo Log、Redo Log和Binlog
    家庭安全不容小觑!青犀AI智能分析算法+摄像头助力家庭安全
    C++ 构造函数
    git commit规范
    PHP 车辆租赁系统mysql数据库web结构apache计算机软件工程网页wamp
    2023 css新特性简单总结
    JUC-管程
  • 原文地址:https://blog.csdn.net/EDT777/article/details/127671695