仅在所有服务可用时如何启动apollo联合服务器

问题描述 投票:1回答:1

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

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
1个回答
0
投票

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

以下是根据服务的可用性如何利用阿波罗网关的演示。基本上,您包装了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

© www.soinside.com 2019 - 2024. All rights reserved.