zhaowenyu
2026-01-14 2eac3f431dbcb048000fca1d83085eb772e01658
ard-sample/src/main/java/com/ard/sample/component/websocket/handler/DockWebSocketHandler.java
@@ -1,7 +1,6 @@
package com.ard.sample.component.websocket.handler;
import com.alibaba.fastjson2.JSON;
import com.ard.sample.common.model.ResponseResult;
import com.ard.sample.component.websocket.enums.MessageType;
import com.ard.sample.component.websocket.model.Payload;
import com.ard.sample.component.websocket.model.WebSocketMessage;
@@ -14,6 +13,7 @@
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import javax.annotation.PreDestroy;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
@@ -21,6 +21,10 @@
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
 * WebSocket处理器(设备对接)
 * 核心能力:心跳检测、订阅/取消订阅、定向消息推送、广播消息
 */
@Slf4j
@Component
public class DockWebSocketHandler extends TextWebSocketHandler {
@@ -31,108 +35,150 @@
    @Autowired
    private IControlService _controlService;
    // ====================== 心跳相关常量 ======================
    /** 心跳间隔(秒):客户端需每隔此时间发一次ping */
    // ====================== 心跳相关常量(可配置化建议放到配置文件) ======================
    /** 心跳间隔(秒):客户端需每隔此时间发送一次PING消息 */
    private static final long HEARTBEAT_INTERVAL = 30;
    /** 心跳超时阈值(秒):超过此时间没收到ping,判定连接失效 */
    /** 心跳超时阈值(秒):超过此时间未收到PING则判定连接失效 */
    private static final long HEARTBEAT_TIMEOUT = 90;
    /** 心跳检测任务间隔(秒):定时检查超时连接 */
    private static final long CHECK_INTERVAL = 10;
    /** 心跳检测任务间隔(秒):定时扫描超时连接 */
    private static final long HEARTBEAT_CHECK_INTERVAL = 10;
    // ====================== 核心存储 ======================
    // 存储用户会话:userId -> WebSocketSession
    // ====================== 核心存储(线程安全) ======================
    /** 用户会话映射:userId -> WebSocketSession */
    private final Map<String, WebSocketSession> userSessions = new ConcurrentHashMap<>();
    // 订阅关系:key=订阅标识(sn+type),value=订阅用户ID集合
    /** 订阅关系映射:订阅标识(sn:type) -> 订阅用户ID集合 */
    private final Map<String, Set<String>> subscriptions = new ConcurrentHashMap<>();
    // 关键:为每个WebSocketSession分配独立的锁对象,确保写操作同步
    /** 会话锁映射:WebSocketSession -> 独立锁对象(防止并发写冲突) */
    private final Map<WebSocketSession, Object> sessionLocks = new ConcurrentHashMap<>();
    // 存储用户最后心跳时间:userId -> 最后心跳时间戳(毫秒)
    /** 用户最后心跳时间:userId -> 最后心跳时间戳(毫秒) */
    private final Map<String, Long> userLastHeartbeatTime = new ConcurrentHashMap<>();
    // ====================== 线程池 ======================
    // 延时任务线程池(单线程,守护线程),用于处理连接关闭后的延时清理
    private final ScheduledExecutorService delayExecutor = Executors.newSingleThreadScheduledExecutor(runnable -> {
        Thread thread = new Thread(runnable, "websocket-关闭-延迟-线程");
        thread.setDaemon(true); // 设为守护线程,不阻塞JVM退出
        return thread;
    });
    // 心跳检测线程池(单线程,守护线程),定时检查超时连接
    /** 心跳检测线程池(单线程守护线程) */
    private final ScheduledExecutorService heartbeatCheckExecutor = Executors.newSingleThreadScheduledExecutor(runnable -> {
        Thread thread = new Thread(runnable, "websocket-心跳检测-线程");
        thread.setDaemon(true);
        Thread thread = new Thread(runnable, "websocket-heartbeat-check-thread");
        thread.setDaemon(true); // 守护线程,不阻塞JVM退出
        return thread;
    });
    // ====================== 初始化心跳检测任务 ======================
    // ====================== 初始化 ======================
    public DockWebSocketHandler() {
        // 项目启动后,每隔 CHECK_INTERVAL 秒执行一次心跳检测
        heartbeatCheckExecutor.scheduleAtFixedRate(this::checkHeartbeatTimeout,
                CHECK_INTERVAL, CHECK_INTERVAL, TimeUnit.SECONDS);
        // 启动心跳检测定时任务:首次延迟CHECK_INTERVAL执行,之后每隔CHECK_INTERVAL执行
        heartbeatCheckExecutor.scheduleAtFixedRate(
                this::checkHeartbeatTimeout,
                HEARTBEAT_CHECK_INTERVAL,
                HEARTBEAT_CHECK_INTERVAL,
                TimeUnit.SECONDS
        );
        log.info("WebSocket心跳检测任务已启动,检测间隔:{}秒,超时阈值:{}秒",
                HEARTBEAT_CHECK_INTERVAL, HEARTBEAT_TIMEOUT);
    }
    // ====================== 连接生命周期 ======================
    /**
     * 连接建立后回调
     * 连接建立成功回调
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 从会话属性中获取认证后的用户ID
        // 从会话属性获取认证后的用户ID(需前置拦截器完成认证)
        String userId = (String) session.getAttributes().get("userId");
        if (userId == null) {
            session.close(CloseStatus.POLICY_VIOLATION.withReason("未认证"));
            session.close(CloseStatus.POLICY_VIOLATION.withReason("未认证,拒绝连接"));
            log.warn("WebSocket连接建立失败:会话无用户认证信息");
            return;
        }
        // 初始化会话相关存储
        userSessions.put(userId, session);
        // 为新会话初始化锁对象
        sessionLocks.put(session, new Object());
        // 初始化用户最后心跳时间(连接建立即视为一次心跳)
        userLastHeartbeatTime.put(userId, System.currentTimeMillis());
        log.info("用户[{}]已连接,当前在线人数:{}", userId, userSessions.size());
        log.info("用户[{}]WebSocket连接建立成功,当前在线人数:{}", userId, userSessions.size());
    }
    /**
     * 处理客户端发送的消息(包含心跳消息)
     * 连接关闭回调(同步清理,无延时)
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        String userId = (String) session.getAttributes().get("userId");
        if (userId != null) {
            // 同步清理所有关联数据
            userSessions.remove(userId);
            sessionLocks.remove(session);
            userLastHeartbeatTime.remove(userId);
            removeUserAllSubscriptions(userId);
            log.info("用户[{}]WebSocket连接关闭(状态码:{},原因:{}),当前在线人数:{}",
                    userId, status.getCode(), status.getReason(), userSessions.size());
        } else {
            // 无认证用户直接清理锁
            sessionLocks.remove(session);
            log.warn("无认证用户WebSocket连接关闭,状态码:{}", status.getCode());
        }
    }
    // ====================== 消息处理 ======================
    /**
     * 处理客户端文本消息(包含心跳、订阅/取消订阅)
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String userId = (String) session.getAttributes().get("userId");
        String jsonMessage = message.getPayload();
        if (userId == null) {
            sendMessage(session, "未认证,无法处理消息");
            return;
        }
        String jsonPayload = message.getPayload();
        try {
            // 解析客户端消息
            WebSocketMessage webSocketMessage = JSON.parseObject(jsonMessage, WebSocketMessage.class);
            String type = webSocketMessage.getType();
            // 解析WebSocket消息体
            WebSocketMessage webSocketMessage = JSON.parseObject(jsonPayload, WebSocketMessage.class);
            String messageType = webSocketMessage.getType();
            Payload payload = webSocketMessage.getPayload();
            // ====================== 处理心跳消息 ======================
            if (MessageType.PING.getType().equals(type)) {
                // 1. 更新用户最后心跳时间
                userLastHeartbeatTime.put(userId, System.currentTimeMillis());
                // 2. 回复pong消息
                WebSocketMessage pongMessage = new WebSocketMessage();
                pongMessage.setType(MessageType.PONG.getType());
                pongMessage.setPayload(new Payload()); // 空payload即可
                sendMessage(session, JSON.toJSONString(pongMessage));
                log.debug("用户[{}]心跳检测成功,已回复pong", userId);
                System.out.println("用户["+userId+"]心跳检测成功,已回复pong");
                return; // 心跳消息无需走后续订阅逻辑
            }
            // 验证消息类型是否合法
            if (!MessageType.fromString(type)) {
                sendMessage(session, "不支持的消息类型:" + type);
            // 1. 处理心跳PING消息
            if (MessageType.PING.getType().equals(messageType)) {
                handleHeartbeatPing(session, userId);
                return;
            }
            // 处理订阅/取消订阅
            handleSubscription(userId, type, payload);
            // 2. 验证消息类型合法性
            if (!MessageType.fromString(messageType)) {
                sendMessage(session, "不支持的消息类型:" + messageType);
                log.warn("用户[{}]发送非法消息类型:{}", userId, messageType);
                return;
            }
            // 3. 处理订阅/取消订阅逻辑
            handleSubscription(userId, messageType, payload);
            // 直播类型订阅:触发开启直播
            if (MessageType.LIVESTREAM.getType().equals(messageType) && payload.isSubscribe()) {
                String sn = payload.getSn();
                _liveStreamService.StartLiveStreaming(sn,userId);
                log.info("设备[{}]直播流已开启(用户[{}]订阅触发)", sn, userId);
            }
        } catch (Exception e) {
            log.error("用户[{}]消息处理错误", userId, e);
            sendMessage(session, "消息格式错误");
            log.error("用户[{}]消息处理异常", userId, e);
            sendMessage(session, "消息格式错误或处理失败:" + e.getMessage());
        }
    }
    /**
     * 处理心跳PING消息
     */
    private void handleHeartbeatPing(WebSocketSession session, String userId) throws IOException {
        // 更新最后心跳时间
        userLastHeartbeatTime.put(userId, System.currentTimeMillis());
        // 回复PONG消息
        WebSocketMessage pongMessage = new WebSocketMessage();
        pongMessage.setType(MessageType.PONG.getType());
        pongMessage.setPayload(new Payload());
        sendMessage(session, JSON.toJSONString(pongMessage));
        log.debug("用户[{}]心跳PING接收成功,已回复PONG", userId);
    }
    /**
@@ -140,91 +186,67 @@
     */
    private void handleSubscription(String userId, String type, Payload payload) {
        String sn = payload.getSn();
        boolean subscribe = payload.isSubscribe();
        String subscriptionKey = getSubscriptionKey(sn, type); // 生成唯一订阅标识
        boolean isSubscribe = payload.isSubscribe();
        String subscriptionKey = getSubscriptionKey(sn, type);
        if (subscribe) {
            // 订阅操作
        if (isSubscribe) {
            // 订阅操作:不存在则创建,存在则添加用户
            subscriptions.computeIfAbsent(subscriptionKey, k -> ConcurrentHashMap.newKeySet()).add(userId);
            log.info("用户[{}]订阅了 设备[{}]的[{}]类型消息", userId, sn, type);
            if (MessageType.LIVESTREAM.getType().equals(type)) {
                // 开启直播
                log.info("开启设备[{}]直播", sn);
                _liveStreamService.StartLiveStreaming(sn);
            }
//            log.info("用户[{}]订阅设备[{}]的[{}]类型消息", userId, sn, type);
//            // 直播类型订阅:触发开启直播
//            if (MessageType.LIVESTREAM.getType().equals(type)) {
//                _liveStreamService.StartLiveStreaming(sn);
//                log.info("设备[{}]直播流已开启(用户[{}]订阅触发)", sn, userId);
//            }
        } else {
            // 取消订阅操作
            if (subscriptions.containsKey(subscriptionKey)) {
                subscriptions.get(subscriptionKey).remove(userId);
                if (subscriptions.get(subscriptionKey).isEmpty()) {
                Set<String> subscriberIds = subscriptions.get(subscriptionKey);
                subscriberIds.remove(userId);
                log.info("用户[{}]取消订阅设备[{}]的[{}]类型消息", userId, sn, type);
                // 订阅组为空时移除,并停止直播(直播类型)
                if (subscriberIds.isEmpty()) {
                    subscriptions.remove(subscriptionKey);
                    // 若取消的是直播订阅且无其他订阅者,停止直播
                    if (MessageType.LIVESTREAM.getType().equals(type)) {
                        log.info("设备[{}]无订阅者,停止直播", sn);
                        _liveStreamService.StopLiveStreaming(sn);
                        log.info("设备[{}]直播流已停止(无订阅用户)", sn);
                    }
                }
                log.info("用户[{}]取消订阅了 设备[{}]的[{}]类型消息", userId, sn, type);
            }
        }
    }
    // ====================== 心跳检测 ======================
    /**
     * 连接关闭后回调
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        String userId = (String) session.getAttributes().get("userId");
        if (userId != null) {
            log.info("用户[{}]连接关闭(状态码:{}),将延时5秒执行清理操作", userId, status.getCode());
            // 延时5秒执行清理逻辑
            delayExecutor.schedule(() -> {
                try {
                    // 清理核心存储
                    userSessions.remove(userId);
                    sessionLocks.remove(session);
                    userLastHeartbeatTime.remove(userId); // 清理心跳时间
                    // 清除该用户的所有订阅
                    removeUserAllSubscriptions(userId);
                    log.info("用户[{}]延时5秒清理完成,当前在线人数:{}", userId, userSessions.size());
                } catch (Exception e) {
                    log.error("用户[{}]延时清理操作异常", userId, e);
                }
            }, 5, TimeUnit.SECONDS); // 延时5秒执行
        } else {
            // 无认证用户,直接清理
            sessionLocks.remove(session);
            log.info("无认证用户连接关闭,直接清理会话锁");
        }
    }
    /**
     * 心跳超时检测:断开超过HEARTBEAT_TIMEOUT未发心跳的用户
     * 检测心跳超时连接并主动关闭
     */
    private void checkHeartbeatTimeout() {
        long currentTime = System.currentTimeMillis();
        // 遍历所有在线用户,检查心跳超时
        // 遍历所有用户心跳记录,检查超时
        for (Map.Entry<String, Long> entry : userLastHeartbeatTime.entrySet()) {
            String userId = entry.getKey();
            Long lastHeartbeat = entry.getValue();
            WebSocketSession session = userSessions.get(userId);
            long lastHeartbeatTime = entry.getValue();
            long timeoutMs = currentTime - lastHeartbeatTime;
            // 1. 计算超时时间差
            long timeoutDiff = currentTime - lastHeartbeat;
            if (timeoutDiff > HEARTBEAT_TIMEOUT * 1000) {
                log.warn("用户[{}]心跳超时({}秒未发ping),将断开连接", userId, timeoutDiff / 1000);
            // 判定超时:超过阈值则主动关闭连接
            if (timeoutMs > HEARTBEAT_TIMEOUT * 1000) {
                WebSocketSession session = userSessions.get(userId);
                log.warn("用户[{}]心跳超时({}秒未发送PING),将主动关闭连接",
                        userId, timeoutMs / 1000);
                try {
                    // 2. 主动关闭连接
                    // 主动关闭连接
                    if (session != null && session.isOpen()) {
                        session.close(CloseStatus.SESSION_NOT_RELIABLE.withReason("心跳超时"));
                        session.close(CloseStatus.SESSION_NOT_RELIABLE.withReason(
                                String.format("心跳超时:%d秒未收到PING", timeoutMs / 1000)
                        ));
                    }
                } catch (IOException e) {
                    log.error("关闭用户[{}]超时连接失败", userId, e);
                    log.error("主动关闭用户[{}]超时连接失败", userId, e);
                } finally {
                    // 3. 清理该用户的所有数据
                    // 强制清理用户所有关联数据
                    userSessions.remove(userId);
                    sessionLocks.remove(session);
                    userLastHeartbeatTime.remove(userId);
@@ -234,69 +256,90 @@
        }
    }
    // ====================== 消息推送接口 ======================
    /**
     * 清除用户的所有订阅
     * 向订阅指定设备指定类型的用户推送消息
     *
     * @param sn      设备序列号
     * @param type    消息类型(对应MessageType)
     * @param content 消息内容(JSON字符串)
     */
    private void removeUserAllSubscriptions(String userId) {
        // 遍历所有订阅,移除该用户并检查是否需要停止直播
        Iterator<Map.Entry<String, Set<String>>> iterator = subscriptions.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Set<String>> entry = iterator.next();
            Set<String> userIds = entry.getValue();
            if (userIds.contains(userId)) {
                userIds.remove(userId);
                // 若订阅组为空,移除并停止直播(如果是直播类型)
                if (userIds.isEmpty()) {
                    String subscriptionKey = entry.getKey();
                    if (subscriptionKey.contains(MessageType.LIVESTREAM.getType())) {
                        String sn = subscriptionKey.split(":")[0];
                        _liveStreamService.StopLiveStreaming(sn);
                        log.info("设备[{}]无订阅者,停止直播", sn);
                    }
                    iterator.remove(); // 安全移除空订阅组
                }
            }
        }
    }
    /**
     * 向订阅了特定设备特定类型的用户发送消息
     */
    public void sendMessageToSubscribers(String sn, String type, String content) {
    public void sendMessageToSubscribers(String sn, String type, String content, String uId) {
        String subscriptionKey = getSubscriptionKey(sn, type);
        Set<String> subscriberIds = subscriptions.getOrDefault(subscriptionKey, new HashSet<>());
        Set<String> subscriberIds = subscriptions.getOrDefault(subscriptionKey, Collections.emptySet());
        if (subscriberIds.isEmpty()) {
            log.debug("设备[{}]的[{}]类型消息无订阅用户,无需推送", sn, type);
            return;
        }
        try {
            for (String userId : subscriberIds) {
                WebSocketSession session = userSessions.get(userId);
                if (session == null || !session.isOpen()) {
                    userSessions.remove(userId);
                    sessionLocks.remove(session);
                    userLastHeartbeatTime.remove(userId); // 清理心跳时间
                    continue;
                }
                // 同步发送消息,避免并发冲突
                Object lock = sessionLocks.get(session);
                if (lock == null) {
                    continue;
                }
                synchronized (lock) {
                    session.sendMessage(new TextMessage(content));
                    log.debug("向用户[{}]发送 设备[{}]的[{}]类型消息:{}", userId, sn, type, content);
                }
        // 遍历订阅用户推送消息
        for (String userId : subscriberIds) {
            WebSocketSession session = userSessions.get(userId);
            if (session == null || !session.isOpen()) {
                // 清理无效会话
                userSessions.remove(userId);
                sessionLocks.remove(session);
                userLastHeartbeatTime.remove(userId);
                log.warn("用户[{}]会话无效,已清理", userId);
                continue;
            }
        } catch (IOException e) {
            log.error("发送消息错误:{}", e.getMessage());
            // 线程安全发送消息
            try {
                if(MessageType.LIVESTREAM.getType().equals(type)) {
                    WebSocketSession liveSession = userSessions.get(uId);
                    sendMessage(liveSession, content);
                    log.info("单独向用户[{}]推送设备[{}]的[{}]类型消息:{}", uId, sn, type, content);
                    return;
                }
                sendMessage(session, content);
                log.debug("向用户[{}]推送设备[{}]的[{}]类型消息:{}", userId, sn, type, content);
            } catch (IOException e) {
                log.error("向用户[{}]推送消息失败", userId, e);
            }
        }
    }
    /**
     * 通用发送消息方法(封装同步逻辑)
     * 新增:向所有在线客户端广播消息
     *
     * @param content 消息内容(JSON字符串)
     */
    public void broadcastMessageToAllClients(String content) {
        if (userSessions.isEmpty()) {
            log.debug("无在线客户端,无需广播消息");
            return;
        }
        // log.info("开始向所有在线客户端({}人)广播消息", userSessions.size());
        // 遍历所有在线会话发送消息
        for (Map.Entry<String, WebSocketSession> entry : userSessions.entrySet()) {
            String userId = entry.getKey();
            WebSocketSession session = entry.getValue();
            if (session == null || !session.isOpen()) {
                // 清理无效会话
                userSessions.remove(userId);
                sessionLocks.remove(session);
                userLastHeartbeatTime.remove(userId);
                log.warn("用户[{}]会话无效,已清理", userId);
                continue;
            }
            // 线程安全发送广播消息
            try {
                sendMessage(session, content);
                log.debug("向用户[{}]广播消息成功", userId);
            } catch (IOException e) {
                log.error("向用户[{}]广播消息失败", userId, e);
            }
        }
    }
    // ====================== 通用工具方法 ======================
    /**
     * 线程安全发送消息(封装同步逻辑)
     */
    private void sendMessage(WebSocketSession session, String content) throws IOException {
        Object lock = sessionLocks.get(session);
@@ -308,28 +351,61 @@
    }
    /**
     * 生成订阅标识(sn+type的组合)
     * 生成订阅标识(设备SN + 消息类型)
     */
    private String getSubscriptionKey(String sn, String type) {
        return sn + ":" + type;
        return String.format("%s:%s", sn, type);
    }
    // ====================== 销毁线程池(可选,防止内存泄漏) ======================
    /**
     * 清除用户所有订阅关系
     */
    private void removeUserAllSubscriptions(String userId) {
        // 迭代器遍历,避免并发修改异常
        Iterator<Map.Entry<String, Set<String>>> iterator = subscriptions.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Set<String>> entry = iterator.next();
            Set<String> subscriberIds = entry.getValue();
    public void destroy() {
        delayExecutor.shutdown();
        heartbeatCheckExecutor.shutdown();
        try {
            if (!delayExecutor.awaitTermination(1, TimeUnit.SECONDS)) {
                delayExecutor.shutdownNow();
            // 移除当前用户
            if (subscriberIds.remove(userId)) {
                log.debug("用户[{}]已移除订阅:{}", userId, entry.getKey());
                // 订阅组为空时移除,并停止直播(直播类型)
                if (subscriberIds.isEmpty()) {
                    String subscriptionKey = entry.getKey();
                    if (subscriptionKey.contains(MessageType.LIVESTREAM.getType())) {
                        String sn = subscriptionKey.split(":")[0];
                        _liveStreamService.StopLiveStreaming(sn);
                        log.info("设备[{}]无订阅用户,已停止直播流", sn);
                    }
                    iterator.remove(); // 安全移除空订阅组
                }
            }
            if (!heartbeatCheckExecutor.awaitTermination(1, TimeUnit.SECONDS)) {
                heartbeatCheckExecutor.shutdownNow();
            }
        } catch (InterruptedException e) {
            delayExecutor.shutdownNow();
            heartbeatCheckExecutor.shutdownNow();
        }
        log.info("WebSocket线程池已销毁");
    }
    // ====================== 资源销毁 ======================
    /**
     * 容器销毁时关闭线程池,防止内存泄漏
     */
    @PreDestroy
    public void destroy() {
        // 关闭心跳检测线程池
        if (heartbeatCheckExecutor != null && !heartbeatCheckExecutor.isShutdown()) {
            heartbeatCheckExecutor.shutdown();
            try {
                // 等待1秒优雅关闭,超时则强制关闭
                if (!heartbeatCheckExecutor.awaitTermination(1, TimeUnit.SECONDS)) {
                    heartbeatCheckExecutor.shutdownNow();
                    log.warn("WebSocket心跳检测线程池强制关闭");
                }
            } catch (InterruptedException e) {
                heartbeatCheckExecutor.shutdownNow();
                Thread.currentThread().interrupt(); // 恢复中断状态
                log.error("WebSocket心跳检测线程池关闭被中断", e);
            }
        }
        log.info("WebSocket处理器资源已销毁");
    }
}