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

如何使用Apollo Gateway加载预联合的Supergraph Schema?

使用预生成的Supergraph Schema配置Apollo Gateway

完全可以实现这个需求——Apollo Gateway支持直接加载本地预先生成的supergraph SDL,同时在运行时将请求代理到对应的子图端点,无需依赖IntrospectAndCompose从远程拉取schema。

实现步骤

  1. 加载本地Supergraph Schema

    • 从文件读取:使用Node.js的fs模块读取预生成的schema文件(比如supergraph.graphql)
    • 直接用字符串:如果schema内容不多,也可以直接将SDL字符串写入代码中
  2. 配置Apollo Gateway

    • 实例化ApolloGateway时,通过supergraphSdl参数传入加载好的schema内容
    • 实现buildService方法,为每个子图创建LocalGraphQLDataSource,指定子图的实际端点,确保运行时请求能被代理过去

代码示例

const { ApolloServer } = require('@apollo/server');
const { startStandaloneServer } = require('@apollo/server/standalone');
const { ApolloGateway, LocalGraphQLDataSource } = require('@apollo/gateway');
const fs = require('fs');

// 从本地文件加载预生成的supergraph schema
const supergraphSdl = fs.readFileSync('./supergraph.graphql', 'utf8');

// 配置网关
const gateway = new ApolloGateway({
  supergraphSdl,
  // 为每个子图配置数据源,代理请求到对应端点
  buildService({ name, url }) {
    return new LocalGraphQLDataSource(url);
  },
});

// 创建并启动Apollo服务器
const server = new ApolloServer({ gateway });

startStandaloneServer(server, { listen: { port: 4000 } })
  .then(({ url }) => console.log(`🚀 网关服务已启动,地址:${url}`));

注意事项

  • 确保buildService中的子图name和url与你使用rover supergraph compose时配置的子图信息完全一致
  • 如果不想读取文件,直接将SDL字符串赋值给supergraphSdl即可,比如:
    const supergraphSdl = `
      type Query {
        users: [User]
        products: [Product]
      }
      # 其他schema定义...
    `;
    
  • 这种配置方式下,网关启动时不会再向子图发起schema查询,完全依赖本地预生成的supergraph SDL,运行时仅负责将请求转发到对应子图处理

内容的提问来源于stack exchange,提问作者Joey Yi Zhao

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 17:52:10