Administrator
2026-11-07 fdb6650b5fde2d39fa06568e4e234d8264c053e2
src/main/java/com/xcong/excoin/modules/gateApi/GateKlineWebSocketClient.java
@@ -12,6 +12,7 @@
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;
@@ -121,6 +122,17 @@
    /** 设置全部频道订阅完成回调(由 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 -> {
        Thread t = new Thread(r, "gate-ws-worker");
@@ -192,6 +204,7 @@
        if (pongTimeoutFuture != null) {
            pongTimeoutFuture.cancel(true);
        }
        cancelSubscribeTimeout();
        shutdownExecutorGracefully(heartbeatExecutor);
        shutdownExecutorGracefully(sharedExecutor);
@@ -251,6 +264,14 @@
                            handler.subscribe(webSocketClient);
                        }
                        sendPing();
                        // 订阅确认超时保护:若服务器既不回 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] 应用正在关闭,忽略连接成功回调");
                    }
@@ -269,6 +290,7 @@
                    isConnected.set(false);
                    isConnecting.set(false);
                    cancelPongTimeout();
                    cancelSubscribeTimeout();
                    scheduleReconnect();
                }
@@ -322,6 +344,8 @@
                }
                // 全部频道订阅完成(含重连后的重新订阅)→ 通知持仓对账等逻辑
                if (areAllSubscribed()) {
                    cancelSubscribeTimeout();
                    resubscribeRetryCount.clear();
                    Runnable cb = onAllSubscribedCallback;
                    if (cb != null) {
                        cb.run();
@@ -334,11 +358,12 @@
                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)) {
@@ -453,6 +478,74 @@
        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 ----
    /**