| | |
| | | import java.util.List; |
| | | import java.util.concurrent.*; |
| | | import java.util.concurrent.atomic.AtomicBoolean; |
| | | import java.util.concurrent.atomic.AtomicInteger; |
| | | import java.util.concurrent.atomic.AtomicReference; |
| | | |
| | | /** |
| | |
| | | * <h3>生命周期</h3> |
| | | * <pre> |
| | | * init() → connect() → startHeartbeat() |
| | | * destroy() → unsubscribe 所有 handler → closeBlocking() → shutdown 线程池 |
| | | * onClose() → reconnectWithBackoff() (最多 3 次,指数退避) |
| | | * destroy() → destroyed=true → unsubscribe 所有 handler → closeBlocking() → shutdown 线程池 |
| | | * onClose() → scheduleReconnect() → reconnectWithBackoff()(无限重试,指数退避,上限 60s) |
| | | * </pre> |
| | | * |
| | | * <h3>消息路由</h3> |
| | |
| | | * 4. update/all → 遍历 channelHandlers → handler.handleMessage(response) |
| | | * </pre> |
| | | * |
| | | * <h3>心跳机制</h3> |
| | | * 采用双重检测:TCP 层的 WebSocket ping/pong + 应用层 futures.ping/futures.pong。 |
| | | * 10 秒未收到任何消息 → 发送 futures.ping;25 秒周期检查。 |
| | | * <h3>心跳与断线检测(双层)</h3> |
| | | * <ol> |
| | | * <li>TCP 层:Java-WebSocket 自带 ping/pong 保活({@code connectionLostTimeout = 30s}), |
| | | * 半开连接(对端静默丢包、无 FIN/RST)会在 30 秒内被库判定丢失并触发 onClose。</li> |
| | | * <li>应用层:{@code futures.ping}/{@code futures.pong}。10 秒未收到任何消息 → 发 ping; |
| | | * 45 秒未收到任何消息 → 判定连接死亡,主动 close → onClose → 重连。</li> |
| | | * </ol> |
| | | * |
| | | * <h3>重连策略</h3> |
| | | * 无限次重试:5s → 10s → 20s → 40s → 60s(封顶),连接成功(onOpen)后归零。 |
| | | * destroy() 后立即停止重连。 |
| | | * |
| | | * <h3>线程安全</h3> |
| | | * 连接状态用 AtomicBoolean(isConnected, isConnecting, isInitialized)。 |
| | | * 连接状态用 AtomicBoolean(isConnected, isConnecting, isInitialized, destroyed, reconnectInProgress)。 |
| | | * 消息时间戳用 AtomicReference。心跳任务用 synchronized 保护。 |
| | | * |
| | | * @author Administrator |
| | |
| | | |
| | | private static final String FUTURES_PING = "futures.ping"; |
| | | private static final String FUTURES_PONG = "futures.pong"; |
| | | /** 静默超过该秒数 → 发送 futures.ping */ |
| | | private static final int HEARTBEAT_TIMEOUT = 10; |
| | | /** 静默超过该秒数 → 判定连接死亡,主动断开重连 */ |
| | | private static final int DEAD_TIMEOUT_SECONDS = 45; |
| | | /** Java-WebSocket 库层 ping/pong 保活超时(秒),用于检测半开 TCP 连接 */ |
| | | private static final int CONNECTION_LOST_TIMEOUT_SECONDS = 30; |
| | | /** 重连初始延迟(毫秒) */ |
| | | private static final long INITIAL_RECONNECT_DELAY_MS = 5000; |
| | | /** 重连最大延迟(毫秒),指数退避封顶值 */ |
| | | private static final long MAX_RECONNECT_DELAY_MS = 60000; |
| | | |
| | | /** WebSocket 地址,由 GateConfig 提供 */ |
| | | private final String wsUrl; |
| | |
| | | private final AtomicBoolean isConnecting = new AtomicBoolean(false); |
| | | /** 初始化标记,防重复 init */ |
| | | private final AtomicBoolean isInitialized = new AtomicBoolean(false); |
| | | /** 销毁标记:置位后停止一切重连 */ |
| | | private final AtomicBoolean destroyed = new AtomicBoolean(false); |
| | | /** 重连任务进行中标记,防止 onClose 并发触发多个重连循环 */ |
| | | private final AtomicBoolean reconnectInProgress = new AtomicBoolean(false); |
| | | /** 当前重连次数(连接成功后归零),仅用于日志 */ |
| | | private final AtomicInteger reconnectAttempt = new AtomicInteger(0); |
| | | |
| | | /** 频道处理器列表,通过 addChannelHandler 注册 */ |
| | | private final List<GateChannelHandler> channelHandlers = new ArrayList<>(); |
| | |
| | | } |
| | | |
| | | /** |
| | | * 销毁:取消所有频道订阅 → 关闭 WebSocket 连接 → 关闭线程池。 |
| | | * 销毁:置销毁标记(停止重连)→ 取消所有频道订阅 → 关闭 WebSocket 连接 → 关闭线程池。 |
| | | * |
| | | * <h3>执行顺序</h3> |
| | | * 先取消订阅(等待 500ms 确保发送完成),再 closeBlocking 关闭连接, |
| | |
| | | */ |
| | | public void destroy() { |
| | | log.info("[WS] 开始销毁..."); |
| | | destroyed.set(true); |
| | | |
| | | if (webSocketClient != null && webSocketClient.isOpen()) { |
| | | for (GateChannelHandler handler : channelHandlers) { |
| | |
| | | } |
| | | } |
| | | |
| | | if (sharedExecutor != null && !sharedExecutor.isShutdown()) { |
| | | sharedExecutor.shutdown(); |
| | | } |
| | | |
| | | shutdownExecutorGracefully(heartbeatExecutor); |
| | | if (pongTimeoutFuture != null) { |
| | | pongTimeoutFuture.cancel(true); |
| | | } |
| | | shutdownExecutorGracefully(heartbeatExecutor); |
| | | shutdownExecutorGracefully(sharedExecutor); |
| | | |
| | | log.info("[WS] 销毁完成"); |
| | |
| | | * <h3>连接成功回调</h3> |
| | | * <ol> |
| | | * <li>设置 isConnected=true,isConnecting=false</li> |
| | | * <li>重连计数归零</li> |
| | | * <li>重置心跳计时器</li> |
| | | * <li>依次订阅所有已注册的频道处理器</li> |
| | | * <li>重置各 handler 订阅标记并重新订阅全部频道</li> |
| | | * <li>发送首次 ping</li> |
| | | * </ol> |
| | | * |
| | | * <h3>连接关闭回调</h3> |
| | | * 设置断连状态 → 取消心跳超时 → 异步触发指数退避重连(最多3次)。 |
| | | * 设置断连状态 → 取消心跳超时 → 异步触发无限指数退避重连。 |
| | | * |
| | | * <h3>线程安全</h3> |
| | | * 使用 {@code AtomicBoolean.isConnecting} 防止并发重连。 |
| | | * 使用 {@code AtomicBoolean.isConnecting} 防止并发重连; |
| | | * finally 中保证失败路径下 isConnecting 一定被复位。 |
| | | */ |
| | | private void connect() { |
| | | if (isConnecting.get() || !isConnecting.compareAndSet(false, true)) { |
| | | if (destroyed.get()) { |
| | | log.info("[WS] 已销毁,不再建立连接"); |
| | | return; |
| | | } |
| | | if (!isConnecting.compareAndSet(false, true)) { |
| | | log.info("[WS] 连接进行中,跳过重复请求"); |
| | | return; |
| | | } |
| | |
| | | log.info("[WS] 连接成功"); |
| | | isConnected.set(true); |
| | | isConnecting.set(false); |
| | | reconnectAttempt.set(0); |
| | | if (sharedExecutor != null && !sharedExecutor.isShutdown()) { |
| | | for (GateChannelHandler handler : channelHandlers) { |
| | | handler.setSubscribed(false); |
| | | } |
| | | resetHeartbeatTimer(); |
| | | for (GateChannelHandler handler : channelHandlers) { |
| | | handler.subscribe(webSocketClient); |
| | |
| | | |
| | | @Override |
| | | public void onClose(int code, String reason, boolean remote) { |
| | | log.warn("[WS] 连接关闭, code:{}, reason:{}", code, reason); |
| | | log.warn("[WS] 连接关闭, code:{}, reason:{}, remote:{}", code, reason, remote); |
| | | isConnected.set(false); |
| | | isConnecting.set(false); |
| | | cancelPongTimeout(); |
| | | if (sharedExecutor != null && !sharedExecutor.isShutdown() && !sharedExecutor.isTerminated()) { |
| | | sharedExecutor.execute(() -> { |
| | | try { reconnectWithBackoff(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Exception e) { log.error("[WS] 重连失败", e); } |
| | | }); |
| | | } else { |
| | | log.warn("[WS] 线程池已关闭,不执行重连"); |
| | | } |
| | | scheduleReconnect(); |
| | | } |
| | | |
| | | @Override |
| | | public void onError(Exception ex) { |
| | | log.error("[WS] 发生错误", ex); |
| | | log.error("[WS] 发生错误: {}", ex.toString()); |
| | | isConnected.set(false); |
| | | // 归一化处理:错误后主动关闭 socket,走 onClose → 重连 的路径 |
| | | if (webSocketClient != null && webSocketClient.isOpen()) { |
| | | try { webSocketClient.close(); } catch (Exception e) { log.warn("[WS] 错误后关闭连接失败", e); } |
| | | } |
| | | } |
| | | }; |
| | | webSocketClient.setConnectionLostTimeout(CONNECTION_LOST_TIMEOUT_SECONDS); |
| | | webSocketClient.connect(); |
| | | } catch (URISyntaxException e) { |
| | | log.error("[WS] URI格式错误", e); |
| | | isConnecting.set(false); |
| | | } catch (Exception e) { |
| | | log.error("[WS] 建立连接失败: {}", e.toString()); |
| | | // connect() 抛出异常时可能不会回调 onClose,这里主动调度重连 |
| | | scheduleReconnect(); |
| | | } finally { |
| | | // 任何失败路径都要复位 isConnecting,否则后续重连会被永久跳过 |
| | | if (!isConnected.get()) { |
| | | isConnecting.set(false); |
| | | } |
| | | } |
| | | } |
| | | |
| | |
| | | } |
| | | if ("subscribe".equals(event)) { |
| | | log.info("[WS] {} 订阅成功: {}", channel, response.getJSONObject("result")); |
| | | for (GateChannelHandler handler : channelHandlers) { |
| | | if (channel.equals(handler.getChannelName())) { |
| | | handler.setSubscribed(true); |
| | | break; |
| | | } |
| | | } |
| | | return; |
| | | } |
| | | if ("unsubscribe".equals(event)) { |
| | |
| | | } catch (Exception e) { |
| | | log.error("[WS] 处理消息失败: {}", message, e); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 检查所有已注册的频道是否都已收到订阅成功确认。 |
| | | */ |
| | | public boolean areAllSubscribed() { |
| | | if (channelHandlers.isEmpty()) return false; |
| | | for (GateChannelHandler h : channelHandlers) { |
| | | if (!h.isSubscribed()) return false; |
| | | } |
| | | return true; |
| | | } |
| | | |
| | | // ---- heartbeat ---- |
| | |
| | | } |
| | | |
| | | /** |
| | | * 检查心跳超时:如果距离上次收到消息超过 10 秒,主动发送 futures.ping。 |
| | | * 心跳检查(由 25s 周期任务 + 每次收到消息后 10s 的一次性任务触发): |
| | | * <ol> |
| | | * <li>静默 ≥ {@link #DEAD_TIMEOUT_SECONDS} 秒 → 判定连接死亡(半开 TCP / 对端失联),主动断开触发重连;</li> |
| | | * <li>静默 ≥ {@link #HEARTBEAT_TIMEOUT} 秒 → 发送 futures.ping 探测。</li> |
| | | * </ol> |
| | | */ |
| | | private void checkHeartbeatTimeout() { |
| | | if (!isConnected.get()) return; |
| | | if (System.currentTimeMillis() - lastMessageTime.get() >= HEARTBEAT_TIMEOUT * 1000L) sendPing(); |
| | | if (!isConnected.get() || destroyed.get()) return; |
| | | long silentMs = System.currentTimeMillis() - lastMessageTime.get(); |
| | | if (silentMs >= DEAD_TIMEOUT_SECONDS * 1000L) { |
| | | log.warn("[WS] 已 {} 秒未收到任何消息,判定连接死亡,主动断开重连", silentMs / 1000); |
| | | if (webSocketClient != null) { |
| | | try { webSocketClient.close(); } catch (Exception e) { log.warn("[WS] 主动断开失败", e); } |
| | | } |
| | | return; |
| | | } |
| | | if (silentMs >= HEARTBEAT_TIMEOUT * 1000L) { |
| | | sendPing(); |
| | | } |
| | | } |
| | | |
| | | /** |
| | |
| | | // ---- reconnect ---- |
| | | |
| | | /** |
| | | * 指数退避重连。初始延迟 5 秒,每次翻倍,最多重试 3 次。 |
| | | * 调度重连任务。用 {@code reconnectInProgress} 防并发:onClose 可能被触发多次, |
| | | * 但同一时刻只允许一个重连循环在跑。 |
| | | */ |
| | | private void scheduleReconnect() { |
| | | if (destroyed.get()) { |
| | | log.info("[WS] 已销毁,跳过重连调度"); |
| | | return; |
| | | } |
| | | if (sharedExecutor == null || sharedExecutor.isShutdown() || sharedExecutor.isTerminated()) { |
| | | log.warn("[WS] 线程池已关闭,不执行重连"); |
| | | return; |
| | | } |
| | | if (!reconnectInProgress.compareAndSet(false, true)) { |
| | | log.info("[WS] 已有重连任务进行中,跳过重复调度"); |
| | | return; |
| | | } |
| | | sharedExecutor.execute(() -> { |
| | | try { |
| | | reconnectWithBackoff(); |
| | | } catch (InterruptedException e) { |
| | | Thread.currentThread().interrupt(); |
| | | log.info("[WS] 重连任务被中断"); |
| | | } catch (Exception e) { |
| | | log.error("[WS] 重连失败", e); |
| | | } finally { |
| | | reconnectInProgress.set(false); |
| | | } |
| | | }); |
| | | } |
| | | |
| | | /** |
| | | * 无限指数退避重连:5s → 10s → 20s → 40s → 60s(封顶),直到连接成功或 destroy()。 |
| | | * connect() 为阻塞调用:返回后若 isConnected 未置位则视为失败,继续下一轮。 |
| | | * |
| | | * @throws InterruptedException 线程被中断 |
| | | * @throws InterruptedException 线程被中断(destroy 时) |
| | | */ |
| | | private void reconnectWithBackoff() throws InterruptedException { |
| | | int attempt = 0, maxAttempts = 3; |
| | | long delayMs = 5000; |
| | | while (attempt < maxAttempts) { |
| | | try { Thread.sleep(delayMs); connect(); return; } catch (Exception e) { log.warn("[WS] 第{}次重连失败", attempt + 1, e); delayMs *= 2; attempt++; } |
| | | long delayMs = INITIAL_RECONNECT_DELAY_MS; |
| | | while (!destroyed.get() && !isConnected.get()) { |
| | | int attempt = reconnectAttempt.incrementAndGet(); |
| | | try { |
| | | Thread.sleep(delayMs); |
| | | } catch (InterruptedException e) { |
| | | Thread.currentThread().interrupt(); |
| | | log.info("[WS] 重连等待被中断,停止重连"); |
| | | return; |
| | | } |
| | | if (destroyed.get() || isConnected.get()) return; |
| | | log.info("[WS] 开始第 {} 次重连", attempt); |
| | | try { |
| | | connect(); |
| | | } catch (Exception e) { |
| | | log.warn("[WS] 第 {} 次重连失败: {}", attempt, e.toString()); |
| | | } |
| | | delayMs = Math.min(delayMs * 2, MAX_RECONNECT_DELAY_MS); |
| | | } |
| | | log.error("[WS] 超过最大重试次数({}),放弃重连", maxAttempts); |
| | | if (isConnected.get()) { |
| | | log.info("[WS] 重连成功,共尝试 {} 次", reconnectAttempt.get()); |
| | | } else { |
| | | log.info("[WS] 已销毁,停止重连"); |
| | | } |
| | | } |
| | | |
| | | /** |