2

我想启动一个联合阿波罗服务器:

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

4

1 回答 1

1

在撰写此答案时,阿波罗无法做到这一点。唯一的解决方案是手动监控可用性并相应地利用 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

于 2019-10-02T15:07:54.490 回答