1
zj
2024-08-12 440f0f0b37a10c82e54f402be8d4d99c7406b4d4
websocketSerivce/src/main/java/org/example/websocket/server/WsServer.java
@@ -86,15 +86,21 @@
    private boolean hasReceivedSubscription(Session session) {
        WsBo wsBo = getWsBoForSession(session.getId());
        String s = RedisUtil.get("user_" + wsBo.getUserId());
        if(null == s || s.isEmpty() && !wsBo.getToken().equals(s)){
        String s = RedisUtil.get(wsBo.getUserId().toString());
        if(StringUtils.isEmpty(s) || !wsBo.getToken().equals(s)){
            closeSession(session, "用户未登录");
            Map<String,Integer> map = new HashMap<>();
            map.put("status",1);
            pushMessage(session,JSONUtil.toJsonStr(map));
            return false;
        }
        return wsBo != null;
    }
    @OnError
    public void onError(Session session, @NonNull Throwable throwable) {
        threadLocalData.remove(session.getId());
        wsServers.remove(this);
        log.error("连接发生报错: {}", throwable.getMessage());
        throwable.printStackTrace();
    }
@@ -102,6 +108,7 @@
    @OnClose
    public void onClose() {
        int count = onlineCount.decrementAndGet();
        threadLocalData.remove(session.getId());
        wsServers.remove(this);
        cancelScheduledTasks(); // 取消定时任务
        log.info("服务端断开连接,当前连接的客户端数量为:{}", count);
@@ -119,6 +126,16 @@
        try {
            if(!message.equals("ping")){
                WsBo bean = JSONUtil.toBean(message, WsBo.class);
                if(null == bean){
                    closeSession(session,"没有订阅消息");
                }
                String s = RedisUtil.get(bean.getUserId().toString());
                if(StringUtils.isEmpty(s)){
                    Map<String,Integer> map = new HashMap<>();
                    map.put("status",1);
                    pushMessage(session,JSONUtil.toJsonStr(map));
                    closeSession(session,"没有订阅消息");
                }
                threadLocalData.put(session.getId(), bean);
            }
        }catch (Exception e){
@@ -152,6 +169,7 @@
                            sessionLock.unlock();
                        }
                    } else {
                        closeSession(session, "会话不存在或已关闭");
                        log.error("会话不存在或已关闭,无法发送消息");
                    }
                } catch (Exception e) {
@@ -172,7 +190,18 @@
    private void schedulePushMessage(Session session, String message) throws JsonProcessingException {
        WsBo wsBo = getWsBoForSession(session.getId());
        if (wsBo != null) {
            String s = RedisUtil.get(wsBo.getUserId().toString());
            if(StringUtils.isEmpty(s) || !s.equals(wsBo.getToken())){
                Map<String,Integer> map = new HashMap<>();
                map.put("status",1);
                pushMessage(session,JSONUtil.toJsonStr(map));
                closeSession(session,"登录状态失效");
            }
            long currentTime = System.currentTimeMillis();
            long lastMessageTime = lastMessageTimeMap.getOrDefault(session, 0L);
            int time = wsBo.getTime();
@@ -186,6 +215,8 @@
                // 时间间隔未达到,不发送消息,可以记录日志或者其他操作
//                log.info("距离上次发送消息时间未达到指定间隔,不发送消息。");
            }
        }else{
            pushMessage(session,"没有订阅消息");
        }
    }
    private static final Gson gson = new Gson();
@@ -214,9 +245,16 @@
                    .collect(Collectors.toList());
        }
        //价差
        redisValueMap = redisValueMap.stream()
                .filter(data -> Double.parseDouble(data.getSpread()) >= wsBo.getSpread())
                .collect(Collectors.toList());
        if(wsBo.getSystemFiltration()){
            redisValueMap = redisValueMap.stream()
                    .filter(data -> Double.parseDouble(data.getSpread()) <= wsBo.getSpread())
                    .collect(Collectors.toList());
        }else{
            redisValueMap = redisValueMap.stream()
                    .filter(data -> Double.parseDouble(data.getSpread()) >= wsBo.getSpread() && Double.parseDouble(data.getSpread()) >= 1000)
                    .collect(Collectors.toList());
        }
        //最低金额
        if(null !=  wsBo.getMinAmount()){
            redisValueMap = redisValueMap.stream()
@@ -246,6 +284,7 @@
                    .filter(data -> list.contains(data.getBuyAndSell()))
                    .forEach(data -> data.setMarker(true));
        }
        map.put("uuid",wsBo.getUuid());
        map.put("current",wsBo.getCurrent());
        map.put("sizes",wsBo.getSizes());
        map.put("total",redisValueMap.size());
@@ -322,11 +361,12 @@
    // 关闭会话的方法
    private void closeSession(Session session, String reason) {
        try {
            threadLocalData.remove(session.getId());
            session.close(new CloseReason(CloseReason.CloseCodes.UNEXPECTED_CONDITION, reason));
        } catch (IOException e) {
            log.error("强制断开连接----异常: {}", e.getMessage());
        }
        wsServers.remove(this);
        log.info("客户端未及时发送订阅消息,断开连接");
        log.info(reason);
    }
}