我正在尝试根据this guide为一个代价高昂的查询设置缓存,该查询的结果每天只更改一次。查询耗时7-8秒,大部分时间在DB查询之后,因为必须对从解析器返回的响应进行大量处理。
我使用的是apollo-server-express库,更改插件是apollo-server-plugin-response-cache。
这就是我所做的:
server.js
const { ApolloServer } = require('apollo-server-express')
const responseCachePlugin = require('apollo-server-plugin-response-cache')
const server = new ApolloServer({
typeDefs,
resolvers,
context: async ({ req }) => {
// ...
},
plugins: [responseCachePlugin()]resolvers.js
personDetails: async (root, args, ctx, info) => {
info.cacheControl.setCacheHint({ maxAge: 600 })
const persons = await Person.find({}).populate('details')
// processing the data
return processedData
}我希望解析器运行一次,然后响应应该几乎立即从缓存中返回。这不管用。我做错了什么,或者我还不明白这应该是如何工作的。
我尝试将缓存提示也放在模式中,但没有得到任何更好的结果。
发布于 2020-02-26 14:00:34
应该能行得通。下面是一个有效的示例:
server.ts
import { ApolloServer, gql } from 'apollo-server-express';
import express from 'express';
import responseCachePlugin from 'apollo-server-plugin-response-cache';
const typeDefs = gql`
type Query {
personDetails: String
}
`;
const resolvers = {
Query: {
personDetails: async (root, args, ctx, info) => {
console.log(`[${new Date().toLocaleTimeString()}] Query.personDetails`);
info.cacheControl.setCacheHint({ maxAge: 10 });
return 'This is person details';
},
},
};
const app = express();
const apolloServer = new ApolloServer({
typeDefs,
resolvers,
plugins: [responseCachePlugin()],
});
apolloServer.applyMiddleware({ app });
const server = app.listen({ port: 4000 }, () => {
console.log(`The server is running in http://localhost:4000${apolloServer.graphqlPath}`);
});请求日志:
The server is running in http://localhost:4000/graphql
[1:51:27 PM] Query.personDetails
[1:51:52 PM] Query.personDetails响应头:
cache-control: max-age=10, public在[1:51:27 PM]发送的第一个graphql请求。在接下来的10秒内,所有发送的请求都将命中缓存(默认为内存中的LRU缓存),这意味着graphql解析器personDetails将不会执行。graphql响应将从缓存中读取并发送到客户端。
10秒后,我在[1:51:52 PM]上发送了另一个graphql请求。缓存已过期。因此,此请求不会命中内存中的缓存。graphql解析器将执行并生成一个新值。
源代码:https://github.com/mrdulin/apollo-graphql-tutorial/tree/master/src/stackoverflow/57243105
发布于 2021-11-04 21:40:27
我知道这是一个古老的问题,但它可能会帮助某些人解决Apollo中的服务器端缓存问题。
因此,根据我的理解,只有当来自底层REST API的响应具有控制缓存头时,apollo-server-plugin-response-cache插件才能工作。如果REST API中没有缓存控制标头,可以在restDataSouce GET调用中覆盖它,如下所示。
return this.get(`uri_path`,"", {cacheOptions: { ttl: 1}});
之后,继续在解析器中使用info.cacheControl,如问题片段中的示例所示。那里的maxAge将覆盖cacheOptions中提到的时间。
https://stackoverflow.com/questions/57243105
复制相似问题