| | |
| | | |
| | | // ====================== 线程池 ====================== |
| | | // 延时任务线程池(单线程,守护线程),用于处理连接关闭后的延时清理 |
| | | private final ScheduledExecutorService delayExecutor = Executors.newSingleThreadScheduledExecutor(runnable -> { |
| | | Thread thread = new Thread(runnable, "websocket-关闭-延迟-线程"); |
| | | thread.setDaemon(true); // 设为守护线程,不阻塞JVM退出 |
| | | return thread; |
| | | }); |
| | | // 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 -> { |
| | |
| | | log.info("用户[{}]连接关闭(状态码:{}),将延时5秒执行清理操作", userId, status.getCode()); |
| | | |
| | | // 延时5秒执行清理逻辑 |
| | | delayExecutor.schedule(() -> { |
| | | // delayExecutor.schedule(() -> { |
| | | try { |
| | | // 清理核心存储 |
| | | userSessions.remove(userId); |
| | |
| | | } catch (Exception e) { |
| | | log.error("用户[{}]延时清理操作异常", userId, e); |
| | | } |
| | | }, 5, TimeUnit.SECONDS); // 延时5秒执行 |
| | | // }, 5, TimeUnit.SECONDS); // 延时5秒执行 |
| | | } else { |
| | | // 无认证用户,直接清理 |
| | | sessionLocks.remove(session); |
| | |
| | | |
| | | // ====================== 销毁线程池(可选,防止内存泄漏) ====================== |
| | | |
| | | public void destroy() { |
| | | delayExecutor.shutdown(); |
| | | heartbeatCheckExecutor.shutdown(); |
| | | try { |
| | | if (!delayExecutor.awaitTermination(1, TimeUnit.SECONDS)) { |
| | | delayExecutor.shutdownNow(); |
| | | } |
| | | if (!heartbeatCheckExecutor.awaitTermination(1, TimeUnit.SECONDS)) { |
| | | heartbeatCheckExecutor.shutdownNow(); |
| | | } |
| | | } catch (InterruptedException e) { |
| | | delayExecutor.shutdownNow(); |
| | | heartbeatCheckExecutor.shutdownNow(); |
| | | } |
| | | log.info("WebSocket线程池已销毁"); |
| | | } |
| | | // public void destroy() { |
| | | // delayExecutor.shutdown(); |
| | | // heartbeatCheckExecutor.shutdown(); |
| | | // try { |
| | | // if (!delayExecutor.awaitTermination(1, TimeUnit.SECONDS)) { |
| | | // delayExecutor.shutdownNow(); |
| | | // } |
| | | // if (!heartbeatCheckExecutor.awaitTermination(1, TimeUnit.SECONDS)) { |
| | | // heartbeatCheckExecutor.shutdownNow(); |
| | | // } |
| | | // } catch (InterruptedException e) { |
| | | // delayExecutor.shutdownNow(); |
| | | // heartbeatCheckExecutor.shutdownNow(); |
| | | // } |
| | | // log.info("WebSocket线程池已销毁"); |
| | | // } |
| | | } |