假设我们有两个拥有自己Schema的服务,一个是服务A,另一个是服务B。接下来,我们将通过Apollo联合将两个服务配置与联合网关E提供的入口点相连接。
那么,如果我在服务A中的逻辑中发生了变更,需要在服务B中更新这些变更呢?
这将需要发送一个查询到管家(gateway),询问 Schema 服务B是否要添加一些新字段。我们可以使用Apollo Server的ApolloGateway
来完成此操作。下面是一个示例:
const { ApolloGateway, RemoteGraphQLDataSource } = require('@apollo/gateway');
class RemoteSchemaService extends RemoteGraphQLDataSource {
willSendRequest({ request, context }) {
request.http.headers.set('my-header', context.myHeader);
}
}
const gateway = new ApolloGateway({
serviceList: [
{ name: 'serviceA', url: 'http://localhost:4001/graphql' },
{
name: 'serviceB', url: 'http://localhost:4002/graphql',
dataSource: new RemoteSchemaService()
}
]
});
const server = new ApolloServer({
gateway,
subscriptions: false,
});
server.listen(4000).then(({ url }) => {
console.log(`� Server ready at ${url}`);
});
使用 RemoteGraphQLDataSource
作为数据源将允许我们修改传出请求的标头(headers),并将其传递到下游服务。在这个示例中我们设置了一个叫做 my-header
的标头。
现在,我们可以在服务B中使用 ApolloServerPluginSchemaReporting
来将使用情况的情况发送回AP散列表(Apollo Platform Hash)中心。这样可以确保突变的信息可在适当的时间进行收集。以下是具体示例:
const { ApolloServerPluginSchemaReporting } = require('apollo-server-core');
const server = new ApolloServer({
schema,
plugins: [
ApolloServerPluginSchemaReporting({
// 在这里配置你的上报选项
})
]
});
server.listen().then(({ url }) => {
console.log(`� Server ready at ${url}`);
});
从 ApolloServerPluginSchemaReporting
函数中读取的获得的类似于下面的信息:
[
{
"schemaHash": "c2c26a0f2534744c44ce92ff6c4cbeddbbc