You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Apollo Client与graphql-ws订阅服务器重启后无法自动重连求助

Apollo Client + graphql-ws 订阅自动重连解决方案

核心思路:利用graphql-ws自带重连机制,避免手动定时器导致的多重复订

  • 配置graphql-ws客户端的自动重连参数
    graphql-ws的createClient内置了重连控制逻辑,无需手动用setInterval实现,可通过以下参数精准控制重连行为:

    import { createClient } from 'graphql-ws';
    
    const wsClient = createClient({
      url: 'ws://your-graphql-endpoint',
      retryAttempts: Infinity, // 无限重试直到连接恢复,可根据需求设固定次数
      retryWait: (attemptCount) => {
        // 指数退避算法,避免短时间内频繁请求服务器
        return Math.min(1000 * Math.pow(2, attemptCount), 30000);
      },
      onReconnecting: () => console.log('尝试重新连接订阅服务...'),
      onConnected: () => console.log('订阅连接已恢复'),
    });
    
  • 在Apollo Client中正确配置订阅链接
    将配置好的ws客户端整合到Apollo Client的链路中,确保连接恢复后自动重启订阅:

    import { ApolloClient, InMemoryCache, split, HttpLink } from '@apollo/client';
    import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
    import { getMainDefinition } from '@apollo/client/utilities';
    
    const httpLink = new HttpLink({ uri: 'http://your-graphql-endpoint' });
    const wsLink = new GraphQLWsLink(wsClient);
    
    // 根据操作类型自动切换HTTP/WS链路
    const splitLink = split(
      ({ query }) => {
        const def = getMainDefinition(query);
        return def.kind === 'OperationDefinition' && def.operation === 'subscription';
      },
      wsLink,
      httpLink
    );
    
    const apolloClient = new ApolloClient({
      link: splitLink,
      cache: new InMemoryCache(),
    });
    
  • 避免手动重复订阅的注意事项

    1. 不要在onComplete中使用setInterval:该回调会在订阅终止时触发,重复创建定时器会导致服务恢复后多重复订请求。
    2. 依赖Apollo Client的订阅自动恢复:当ws连接恢复后,useSubscription钩子或手动创建的订阅Observable会自动重新发起订阅,无需额外处理。
    3. 组件中订阅的稳定性:使用useCallback或useMemo包裹订阅参数,避免组件重渲染时重复创建订阅实例:
      import { useSubscription, useCallback } from '@apollo/client';
      import { MY_SUBSCRIPTION } from './graphql/queries';
      
      const MySubscriptionComponent = () => {
        const onSubscriptionData = useCallback(({ data }) => {
          // 处理订阅数据
        }, []);
      
        useSubscription(MY_SUBSCRIPTION, {
          onSubscriptionData,
          onError: (err) => console.error('订阅异常:', err),
        });
      
        // 渲染逻辑
      };
      

内容的提问来源于stack exchange,提问作者Adeveloper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 11:04:58