| | |
| | | import java.net.URISyntaxException; |
| | | import java.util.ArrayList; |
| | | import java.util.List; |
| | | import java.util.Map; |
| | | import java.util.concurrent.*; |
| | | import java.util.concurrent.atomic.AtomicBoolean; |
| | | import java.util.concurrent.atomic.AtomicInteger; |
| | |
| | | private static final String FUTURES_PING = "futures.ping"; |
| | | private static final String FUTURES_PONG = "futures.pong"; |
| | | /** 静默超过该秒数 → 发送 futures.ping 探测(官方文档:客户端 ping 可重置服务端关闭计数) */ |
| | | private static final int HEARTBEAT_TIMEOUT = 10; |
| | | private static final int HEARTBEAT_TIMEOUT = 5; |
| | | /** |
| | | * 静默超过该秒数(且已发出过探测 ping)→ 判定连接不健康,主动断开重连。 |
| | | * 即:10s 静默发 ping,再等 10s 仍无任何消息(连 pong 都没有)→ 判定死亡。 |
| | | * 即:5s 静默发 ping,再等 10s 仍无任何消息(连 pong 都没有)→ 判定死亡。 |
| | | * 缩短该阈值可尽快发现"假活"(半开 TCP)连接,重连只作为兜底而非常态。 |
| | | */ |
| | | private static final int DEAD_TIMEOUT_SECONDS = 20; |
| | | private static final int DEAD_TIMEOUT_SECONDS = 15; |
| | | /** 心跳检查周期(秒):原 25s 太长,假活连接最坏要 45s 才被发现,缩短到 10s */ |
| | | private static final int HEARTBEAT_CHECK_INTERVAL_SECONDS = 10; |
| | | /** 订阅全部完成后链路活性验证窗口(秒):窗口内无任何消息 → 判定假活,立即断开重连 */ |
| | | private static final int POST_SUBSCRIBE_ALIVE_CHECK_SECONDS = 10; |
| | | /** Java-WebSocket 库层 ping/pong 保活超时(秒),用于检测半开 TCP 连接(兜底) */ |
| | | private static final int CONNECTION_LOST_TIMEOUT_SECONDS = 30; |
| | | /** |
| | |
| | | |
| | | /** 频道处理器列表,通过 addChannelHandler 注册 */ |
| | | private final List<GateChannelHandler> channelHandlers = new ArrayList<>(); |
| | | /** 全部频道订阅完成后的回调(首次连接与重连后都会触发,供持仓对账等逻辑使用) */ |
| | | private volatile Runnable onAllSubscribedCallback; |
| | | /** 设置全部频道订阅完成回调(由 GateGridTradeService 挂接,重连后触发持仓对账) */ |
| | | public void setOnAllSubscribedCallback(Runnable callback) { this.onAllSubscribedCallback = callback; } |
| | | |
| | | /** 订阅确认超时(秒):连接建立后超过该时长仍未全部订阅成功 → 判定订阅失败,断开重连 */ |
| | | private static final int SUBSCRIBE_TIMEOUT_SECONDS = 20; |
| | | /** 单频道订阅失败后的重新订阅延迟(秒) */ |
| | | private static final int RESUBSCRIBE_DELAY_SECONDS = 2; |
| | | /** 单频道订阅失败重试次数上限(超过则整体断开重连,重订阅全部频道) */ |
| | | private static final int MAX_RESUBSCRIBE_RETRIES = 3; |
| | | /** 订阅确认超时 Future(连接建立后启动,全部订阅成功或断开时取消) */ |
| | | private volatile ScheduledFuture<?> subscribeTimeoutFuture; |
| | | /** 各频道重新订阅重试计数(channelName → 次数),连接成功后清空 */ |
| | | private final Map<String, AtomicInteger> resubscribeRetryCount = new ConcurrentHashMap<>(); |
| | | |
| | | /** 重连等异步任务的缓存线程池(daemon 线程) */ |
| | | private final ExecutorService sharedExecutor = Executors.newCachedThreadPool(r -> { |
| | |
| | | if (pongTimeoutFuture != null) { |
| | | pongTimeoutFuture.cancel(true); |
| | | } |
| | | cancelSubscribeTimeout(); |
| | | shutdownExecutorGracefully(heartbeatExecutor); |
| | | shutdownExecutorGracefully(sharedExecutor); |
| | | |
| | |
| | | for (GateChannelHandler handler : channelHandlers) { |
| | | handler.subscribe(webSocketClient); |
| | | } |
| | | sendPing(); |
| | | try { |
| | | if (webSocketClient != null && webSocketClient.isOpen()) { |
| | | JSONObject pingMsg = new JSONObject(); |
| | | pingMsg.put("time", System.currentTimeMillis() / 1000); |
| | | pingMsg.put("channel", FUTURES_PING); |
| | | webSocketClient.send(pingMsg.toJSONString()); |
| | | log.debug("[WS] 发送 ping 请求"); |
| | | } |
| | | } catch (Exception e) { log.warn("[WS] 发送 ping 失败", e); } |
| | | // 订阅确认超时保护:若服务器既不回 subscribe 确认、也不回 error, |
| | | // 超时后判定订阅失败断开重连,避免策略永久卡在 WAITING_KLINE |
| | | cancelSubscribeTimeout(); |
| | | resubscribeRetryCount.clear(); |
| | | if (heartbeatExecutor != null && !heartbeatExecutor.isShutdown()) { |
| | | subscribeTimeoutFuture = heartbeatExecutor.schedule( |
| | | () -> checkSubscriptionTimeout(), SUBSCRIBE_TIMEOUT_SECONDS, TimeUnit.SECONDS); |
| | | } |
| | | } else { |
| | | log.warn("[WS] 应用正在关闭,忽略连接成功回调"); |
| | | } |
| | |
| | | isConnected.set(false); |
| | | isConnecting.set(false); |
| | | cancelPongTimeout(); |
| | | cancelSubscribeTimeout(); |
| | | scheduleReconnect(); |
| | | } |
| | | |
| | |
| | | break; |
| | | } |
| | | } |
| | | // 全部频道订阅完成(含重连后的重新订阅)→ 通知持仓对账等逻辑 |
| | | if (areAllSubscribed()) { |
| | | cancelSubscribeTimeout(); |
| | | resubscribeRetryCount.clear(); |
| | | // 订阅确认 ≠ 链路健康(半开连接可能在确认后立刻假死): |
| | | // 立即发 futures.ping,并安排一次活性验证——窗口内无任何消息则判假活重连 |
| | | sendPing(); |
| | | if (heartbeatExecutor != null && !heartbeatExecutor.isShutdown()) { |
| | | heartbeatExecutor.schedule(() -> { |
| | | if (!destroyed.get() && isConnected.get() |
| | | && System.currentTimeMillis() - lastMessageTime.get() |
| | | >= POST_SUBSCRIBE_ALIVE_CHECK_SECONDS * 1000L) { |
| | | log.warn("[WS] 订阅完成后 {} 秒无任何消息,判定链路假活,断开重连", |
| | | POST_SUBSCRIBE_ALIVE_CHECK_SECONDS); |
| | | closeSocket(); |
| | | } |
| | | }, POST_SUBSCRIBE_ALIVE_CHECK_SECONDS, TimeUnit.SECONDS); |
| | | } |
| | | Runnable cb = onAllSubscribedCallback; |
| | | if (cb != null) { |
| | | cb.run(); |
| | | } |
| | | } |
| | | return; |
| | | } |
| | | if ("unsubscribe".equals(event)) { |
| | |
| | | return; |
| | | } |
| | | if ("error".equals(event)) { |
| | | JSONObject error = response.getJSONObject("error"); |
| | | // 官方格式:code/message 在顶层(非嵌套 error 对象) |
| | | log.error("[WS] {} 错误, code:{}, msg:{}", |
| | | channel, |
| | | error != null ? error.getInteger("code") : "N/A", |
| | | error != null ? error.getString("message") : response.getString("msg")); |
| | | response.getInteger("code"), |
| | | response.getString("message")); |
| | | handleChannelSubscribeError(channel); |
| | | return; |
| | | } |
| | | if ("update".equals(event) || "all".equals(event)) { |
| | |
| | | private void startHeartbeat() { |
| | | if (heartbeatExecutor != null && !heartbeatExecutor.isTerminated()) heartbeatExecutor.shutdownNow(); |
| | | heartbeatExecutor = Executors.newSingleThreadScheduledExecutor(r -> { Thread t = new Thread(r, "gate-ws-heartbeat"); t.setDaemon(true); return t; }); |
| | | heartbeatExecutor.scheduleWithFixedDelay(this::checkHeartbeatTimeout, 25, 25, TimeUnit.SECONDS); |
| | | heartbeatExecutor.scheduleWithFixedDelay(this::checkHeartbeatTimeout, |
| | | HEARTBEAT_CHECK_INTERVAL_SECONDS, HEARTBEAT_CHECK_INTERVAL_SECONDS, TimeUnit.SECONDS); |
| | | } |
| | | |
| | | /** |
| | | * 重置心跳计时器:取消旧超时任务,提交新的 10 秒超时检测。 |
| | | * 重置心跳计时器:取消旧超时任务,提交新的 HEARTBEAT_TIMEOUT 秒超时检测。 |
| | | */ |
| | | private synchronized void resetHeartbeatTimer() { |
| | | cancelPongTimeout(); |
| | |
| | | } |
| | | |
| | | /** |
| | | * 心跳检查(由 25s 周期任务 + 每次收到消息后 10s 的一次性任务触发)。 |
| | | * 心跳检查(由 {@link #HEARTBEAT_CHECK_INTERVAL_SECONDS} 秒周期任务 + 每次收到消息后 |
| | | * {@link #HEARTBEAT_TIMEOUT} 秒的一次性任务触发)。 |
| | | * 主动健康检查逻辑(依据 Gate.io 官方文档 ping/pong 语义): |
| | | * <ol> |
| | | * <li>连接存活 ≥ {@link #MAX_CONNECTION_AGE_SECONDS} 秒 → 主动优雅断开重连(主动换线, |
| | | * 绕开链路中间设备约 1 小时的强制断连,把被动盲区变为计划内切换);</li> |
| | | * <li>静默 ≥ {@link #HEARTBEAT_TIMEOUT} 秒 → 发送 futures.ping 探测,并安排 10 秒后复查;</li> |
| | | * <li>静默 ≥ {@link #HEARTBEAT_TIMEOUT} 秒 → 发送 futures.ping 探测,并安排复查;</li> |
| | | * <li>静默 ≥ {@link #DEAD_TIMEOUT_SECONDS} 秒(探测 ping 也得不到任何回应,包括 pong)→ |
| | | * 判定连接不健康,主动断开触发重连。</li> |
| | | * </ol> |
| | |
| | | if (pongTimeoutFuture != null && !pongTimeoutFuture.isDone()) pongTimeoutFuture.cancel(true); |
| | | } |
| | | |
| | | /** |
| | | * 订阅确认超时检查:连接建立后超过 {@link #SUBSCRIBE_TIMEOUT_SECONDS} 秒仍未全部订阅成功 |
| | | * (服务器既不回 subscribe 确认、也不回 error),判定订阅失败,主动断开触发整体重连。 |
| | | */ |
| | | private void checkSubscriptionTimeout() { |
| | | if (destroyed.get() || !isConnected.get()) { |
| | | return; |
| | | } |
| | | if (!areAllSubscribed()) { |
| | | StringBuilder sb = new StringBuilder(); |
| | | for (GateChannelHandler h : channelHandlers) { |
| | | if (!h.isSubscribed()) { |
| | | if (sb.length() > 0) sb.append(','); |
| | | sb.append(h.getChannelName()); |
| | | } |
| | | } |
| | | log.warn("[WS] 连接建立 {} 秒后仍有频道未订阅成功({}), 判定订阅失败,断开重连", |
| | | SUBSCRIBE_TIMEOUT_SECONDS, sb); |
| | | closeSocket(); |
| | | } |
| | | } |
| | | |
| | | /** 取消订阅确认超时任务。 */ |
| | | private void cancelSubscribeTimeout() { |
| | | if (subscribeTimeoutFuture != null && !subscribeTimeoutFuture.isDone()) { |
| | | subscribeTimeoutFuture.cancel(true); |
| | | } |
| | | subscribeTimeoutFuture = null; |
| | | } |
| | | |
| | | /** |
| | | * 频道订阅失败处理:先按频道延迟重新订阅(有限次数),超过上限则整体断开重连。 |
| | | * 覆盖"鉴权失败/订阅参数错误"等 error 场景,避免订阅失败后策略永久卡在 WAITING_KLINE。 |
| | | */ |
| | | private void handleChannelSubscribeError(String channel) { |
| | | if (destroyed.get()) { |
| | | return; |
| | | } |
| | | GateChannelHandler target = null; |
| | | for (GateChannelHandler h : channelHandlers) { |
| | | if (channel.equals(h.getChannelName())) { |
| | | target = h; |
| | | break; |
| | | } |
| | | } |
| | | if (target == null) { |
| | | return; |
| | | } |
| | | target.setSubscribed(false); |
| | | int retries = resubscribeRetryCount.computeIfAbsent(channel, k -> new AtomicInteger()).incrementAndGet(); |
| | | if (retries > MAX_RESUBSCRIBE_RETRIES) { |
| | | log.warn("[WS] {} 重新订阅失败已达 {} 次,断开整体重连", channel, retries - 1); |
| | | closeSocket(); |
| | | return; |
| | | } |
| | | log.warn("[WS] {} 订阅失败(第{}次),{} 秒后重新订阅", channel, retries, RESUBSCRIBE_DELAY_SECONDS); |
| | | if (heartbeatExecutor == null || heartbeatExecutor.isShutdown()) { |
| | | return; |
| | | } |
| | | // target 在查找循环中被赋值,非 effectively final,须用 final 变量捕获进 lambda |
| | | final GateChannelHandler handlerToResubscribe = target; |
| | | heartbeatExecutor.schedule(() -> { |
| | | if (!destroyed.get() && isConnected.get() && webSocketClient != null && webSocketClient.isOpen()) { |
| | | handlerToResubscribe.subscribe(webSocketClient); |
| | | } |
| | | }, RESUBSCRIBE_DELAY_SECONDS, TimeUnit.SECONDS); |
| | | } |
| | | |
| | | // ---- reconnect ---- |
| | | |
| | | /** |