【问题标题】:How to start apollo federation server only when all services are available只有当所有服务都可用时如何启动 apollo federation server
【发布时间】:2023-03-24 15:46:01
【问题描述】:

我想启动一个联合的 apollo 服务器:

const gateway = new ApolloGateway({
  serviceList: [
    ... list of services
  ],
});

const startServer = async () => {
  const gatewayConfig = await gateway.load();
  const server = new ApolloServer({
    ...gatewayConfig,
    subscriptions: false,
  });

  server.listen().then(({ url }) => {
    console.log("Server running!");
  });
};

startServer();

当我启动服务器并且 serviceList 中的一项服务可用时,服务器启动并记录哪些服务失败。我希望服务器仅在所有服务都可用时启动,即当一项服务不可用时,会引发错误并且服务器停止。任何想法如何做到这一点?

【问题讨论】:

    标签: apollo apollo-server apollo-federation


    【解决方案1】:

    截至撰写此答案时,Apollo 无法做到这一点。唯一的解决方案是手动监控可用性并相应地利用 apollo。我为此使用了apollo-server-express

    以下是我如何根据服务的可用性设法利用我的 apollo 网关的演示。
    基本上,你包装了你的 apollo 服务器的中间件。这允许您交换您的 apollo 服务器实例,并在它们不可用时引发错误。

    import express from 'express';
    import { ApolloServer } from 'apollo-server-express';
    import bodyParser from 'body-parser'; // use express body-parser for convinience
    
    // your list of federated services
    const serviceList = [
     { name: 'service1', url: 'http://service1/graphql' }
    ];
    
    // a variable to store the server. We will need to replace him when a service goes offline or comes back online again
    let server = null;
    
    // setup express
    const app = express();
    app.use(bodyParser.json());
    app.use(customRouterToLeverageApolloServer); // defined below
    
    // middleware to leverage apollo server
    function customRouterToLeverageApolloServer(req, res, next) {
      // if services are down (no apollo instance) throw an error
      if(!server) {
        res.json({ error: 'services are currently not available' });
        return;
      }
    
      // else pass the request to apollo
      const router = server.getMiddleware(); // https://www.apollographql.com/docs/apollo-server/api/apollo-server/#apolloservergetmiddleware
      return router(req, res, next);
    }
    
    function servicesAreAvailable() {
      // go through your serviceList and check availability
    }
    
    // periodically check the availability of your services and create/destroy an ApolloServer instance accordingly. This will also be the indication whether or not your services are available at the time.
    // you might want to also call this function at startup
    setInterval(() => {
      if(servicesAreAvailable()) {
        server = new ApolloServer({ ... });
      }
      else {
        server = null;
      }
    }, 1000 * 60 * 5) // check every 5 minutes
    
    

    【讨论】:

      猜你喜欢
      • 2021-03-29
      • 2011-01-25
      • 2020-09-30
      • 1970-01-01
      • 2021-07-27
      • 1970-01-01
      • 2017-10-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多