可以通过在Apollo网关和联合服务之间添加一个中间件来实现缓存。例如,使用Apollo Server插件中的response cache插件,将缓存添加到Apollo Server中,然后在Apollo网关中配置中间件来代理缓存请求,从而实现缓存。
示例代码如下:
// 在Apollo Server中配置response cache插件 const responseCachePlugin = require('apollo-server-plugin-response-cache'); const server = new ApolloServer({ schema, plugins: [responseCachePlugin()] });
// 在Apollo网关中添加中间件 const apolloGateway = new ApolloGateway({ serviceList: [ { name: 'serviceName', url: 'http://serviceUrl' }, // more services ], middlewares: [ responseCacheMiddleware({ // 缓存设置 expiresIn: '1d', excludePaths: ['/health'], // 更多选项 }), ], });
// 将apolloGateway作为Apollo Server的中间件
const app = express();
app.use('/graphql', apolloGateway);
app.listen({ port: 4000 }, () =>
console.log(Gateway ready on http://localhost:4000/graphql
),
);
上一篇:Apollo网关/服务器响应极慢