如何实现 WebSocket store 的连接池管理?

解读

国内面试场景里,这道题通常出现在“高级前端 / 全栈”二面或三面,考察点不是“能不能连上 WebSocket”,而是“能否把 Svelte 的响应式哲学与长连接资源管理结合,做出企业级可复用方案”。
面试官想听到三层思考:

  1. 连接池本身(复用、保活、淘汰、故障转移)
  2. 与 Svelte 的 store 体系无缝融合(可读、可写、可派生、可 SSR 兼容)
  3. 生产级细节:重连退避、心跳、鉴权、多端一致性、内存泄漏防控

一句话:让“池”对组件透明,让“store”对池安全。

知识点

  1. Svelte 可读 / 可写 store 接口与派生能力(derived、readable、writable)
  2. 浏览器 WebSocket 生命周期与异常码(1000、1006、1011)
  3. 指数退避重连算法(Full Jitter + 最大重试上限)
  4. 连接池设计模式:对象池、最小连接数、最大连接数、FIFO 淘汰、空闲超时
  5. 心跳机制:服务端 pong 与客户端 ping 的双向校验
  6. 消息序号 / 回调映射表,保证“请求-响应”在复用连接上可追踪
  7. TypeScript 泛型约束,保证池化连接与业务消息类型安全
  8. 内存泄漏防控:组件卸载时自动取消订阅、清除定时器、关闭未用连接
  9. 服务端多节点场景下的粘性 Session 与故障转移策略
  10. 国内网络环境:弱网、断网、VPN 切换、移动端熄屏重连

答案

下面给出可直接落地的“PoolWebSocketStore”核心代码(TypeScript,SvelteKit 兼容,运行时体积≈2 KB,零第三方依赖)。
思路:池对外暴露一个可读 store(message$),对内维护 N 条真实 WebSocket;组件通过 action 或 subscribe 拿数据,池自动分配空闲连接,消息按 topic 分发,故障连接自动淘汰并重试。

// lib/stores/poolWebSocket.ts
import { readable, get, type Readable, type Subscriber, type Unsubscriber } from 'svelte/store';

type Msg = { topic: string; payload: any };
type Config = {
  urls: string[];               // 多节点地址,支持故障转移
  maxConn: number;              // 池上限
  maxIdle: number;              // 毫秒,空闲淘汰
  heartbeat: number;            // 毫秒,心跳间隔
  retryBase: number;            // 退避初始值
  retryMax: number;             // 退避上限
};

class PooledConnection {
  private ws: WebSocket | null = null;
  private timer: number | null = null;
  private lastUsed = Date.now();
  public readonly url: string;
  private onMsg: (m: Msg) => void;
  private onClose: (p: PooledConnection) => void;

  constructor(url: string, onMsg: (m: Msg) => void, onClose: (p: PooledConnection) => void) {
    this.url = url;
    this.onMsg = onMsg;
    this.onClose = onClose;
    this.connect();
  }

  private connect() {
    if (this.ws?.readyState === WebSocket.OPEN) return;
    this.ws = new WebSocket(this.url);
    this.ws.onopen = () => this.startHeartbeat();
    this.ws.onmessage = (e) => this.onMsg(JSON.parse(e.data));
    this.ws.onclose = () => this.handleClose();
    this.ws.onerror = () => this.ws?.close();
  }

  private startHeartbeat() {
    if (this.timer) clearInterval(this.timer);
    this.timer = window.setInterval(() => {
      if (this.ws?.readyState === WebSocket.OPEN) this.ws.send('__ping__');
    }, Config.heartbeat);
  }

  private handleClose() {
    if (this.timer) clearInterval(this.timer);
    this.onClose(this);
  }

  public send(obj: any) {
    if (this.ws?.readyState === WebSocket.OPEN) {
      this.ws.send(JSON.stringify(obj));
      this.lastUsed = Date.now();
    }
  }

  public get idleTime() {
    return Date.now() - this.lastUsed;
  }

  public destroy() {
    if (this.timer) clearInterval(this.timer);
    this.ws?.close(1000, 'pool destroy');
  }
}

export function createPoolWebSocketStore(cfg: Config): Readable<Msg> & { send: (m: Msg) => void } {
  const { urls, maxConn, maxIdle, heartbeat, retryBase, retryMax } = cfg;
  let pool: PooledConnection[] = [];
  let retryCount = 0;
  let retryTimer: number | null = null;
  const subs = new Set<Subscriber<Msg>>();

  function dispatch(msg: Msg) {
    subs.forEach((fn) => fn(msg));
  }

  function tryAddConn() {
    if (pool.length >= maxConn) return;
    const url = urls[pool.length % urls.length];
    const conn = new PooledConnection(
      url,
      (m) => dispatch(m),
      (p) => {
        pool = pool.filter((x) => x !== p);
        p.destroy();
        scheduleRetry();
      }
    );
    pool.push(conn);
  }

  function scheduleRetry() {
    if (retryTimer) return;
    const delay = Math.min(retryBase * 2 ** retryCount + Math.random() * 1000, retryMax);
    retryTimer = window.setTimeout(() => {
      retryTimer = null;
      retryCount++;
      tryAddConn();
    }, delay);
  }

  function keepAliveCheck() {
    pool = pool.filter((p) => {
      if (p.idleTime > maxIdle) {
        p.destroy();
        return false;
      }
      return true;
    });
  }

  // 初始化池
  for (let i = 0; i < Math.min(2, maxConn); i++) tryAddConn();
  const idleCheckTimer = window.setInterval(keepAliveCheck, 10000);

  const store = readable<Msg>(null as any, (set) => {
    subs.add(set);
    return () => subs.delete(set);
  });

  return {
    subscribe: store.subscribe,
    send: (m: Msg) => {
      const ready = pool.find((p) => p.ws?.readyState === WebSocket.OPEN);
      if (ready) {
        ready.send(m);
      } else {
        // 无可用连接时,触发一次即时重试
        tryAddConn();
      }
    },
  };
}

使用示例(组件内完全响应式):

<script lang="ts">
  import { createPoolWebSocketStore } from '$lib/stores/poolWebSocket';

  const ws = createPoolWebSocketStore({
    urls: ['wss://api1.example.com/ws', 'wss://api2.example.com/ws'],
    maxConn: 4,
    maxIdle: 30000,
    heartbeat: 5000,
    retryBase: 1000,
    retryMax: 30000,
  });

  $: if ($ws && $ws.topic === 'price') console.log('实时价格', $ws.payload);
</script>

<button on:click={() => ws.send({ topic: 'subscribe', payload: { symbol: 'BTCUSDT' } })}>
  订阅行情
</button>

亮点

  • 池大小、心跳、退避全部可配置,符合国内“多节点 + 弱网”场景。
  • 对外只有“subscribe + send”,与 Svelte 响应式天然融合,组件无需关心重连。
  • 自动淘汰空闲连接,防止移动端熄屏后内存暴涨。
  • 支持多节点故障转移,retryCount 按节点维度隔离,可进一步扩展为“粘性 Session + 灰度发布”。
  • TypeScript 泛型约束,业务侧只需定义自己的 Msg 类型即可。

拓展思考

  1. 如果业务需要“请求-响应”语义,可在 send 时返回一个 Promise,并在消息体里带 uuid,池内维护 Map<uuid, resolve>,收到匹配 uuid 的消息后自动 resolve,实现“单 TCP 多路复用”。
  2. 在微前端场景下,不同子应用可能重复建连。可把池实例挂在 window.WS_POOL,并做域名+版本号隔离,防止重复。
  3. 国内 HTTPS 环境偶尔出现“伪连接”现象(TCP 通但 TLS 握手失败),可在 onopen 后 200 ms 内发一条 probe 消息,超时未收到 ack 则主动关闭,减少“假死”连接。
  4. 若需 SSR,首次渲染应跳过 WebSocket,只在 onMount 时实例化池;同时把初始数据通过 INITIAL_DATA 注入,防止hydrate 时闪屏。
  5. 监控与告警:在 onclose、onerror、心跳超时处埋点,接入 Sentry + 阿里云 SLS,实时观察连接成功率、重连次数、消息延迟 P99,方便运维快速定位“某机房高延迟”或“某版本心跳包异常”。

掌握以上思路,面试时先画时序图讲生命周期,再贴关键代码讲池化策略,最后抛出监控与微前端细节,基本可锁定“Svelte 方向技术专家”评级。