我要启动联合阿波罗服务器:
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中的一项服务可用时,服务器将启动并记录哪些服务失败。我希望服务器仅在所有服务可用时启动,即,当一项服务不可用时,引发错误并服务器停止。任何想法如何做到这一点?
答案 0 :(得分:0)
在撰写此答案时,Apollo无法做到这一点。唯一的解决方案是手动监视可用性并相应地利用apollo。我为此使用了apollo-server-express
。
下面是如何根据服务的可用性如何利用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