如何使用 apollo-server 进行缓存

7
https://www.apollographql.com/docs/apollo-server/features/data-sources.html#Implementing-your-own-cache-backend的Apollo基础示例中,他们指出实现Redis缓存只需要这么简单:
const { RedisCache } = require('apollo-server-cache-redis');

const server = new ApolloServer({
  typeDefs,
  resolvers,
  cache: new RedisCache({
    host: 'redis-server',
    // Options are passed through to the Redis client
  }),
  dataSources: () => ({
    moviesAPI: new MoviesAPI(),
  }),
});

当我查看非Redis的示例时,它说明这是一个简单的{ get,set }缓存。这意味着理论上我应该能够做到。
cache : {
   get : function() {
     console.log("GET!");
   },
   set : function() {
     console.log("SET!");
   }
}

无论我尝试什么,当我使用apollo-server提供的graphQL explorer时,我的缓存功能从未被调用。
我已经尝试过`cacheControl: true`和像https://medium.com/brikl-engineering/serverless-graphql-cached-in-redis-with-apollo-server-2-0-f491695cac7f中设置的`cacheControl`。但是都没有起作用。
是否有一个示例来实现基本的Apollo缓存,而不使用付费的Apollo Engine系统?

你有Redis服务器吗?为了能够提供缓存响应,您需要Redis服务器memcached服务器,因为该软件包需要在本地主机或另一台服务器上的主机IP地址,即host:'redis-server',其中redis-server是IP地址。 - Mohamad Kaakati
请将一个答案标记为已接受的答案。 - Asma Rahim Ali Jafri
2个回答

1
你可以查看实现了package的代码,以缓存完整响应并实现自己的缓存。

import { RedisCache } from "apollo-server-redis";
import responseCachePlugin from "apollo-server-plugin-response-cache";


 const server = new ApolloServer({
    ...
    plugins: [responseCachePlugin()],
     cache: new RedisCache({
        connectTimeout: 5000,
        reconnectOnError: function(err) {
          Logger.error("Reconnect on error", err);
          const targetError = "READONLY";
          if (err.message.slice(0, targetError.length) === targetError) {
            // Only reconnect when the error starts with "READONLY"
            return true;
          }
        },
        retryStrategy: function(times) {
          Logger.error("Redis Retry", times);
          if (times >= 3) {
            return undefined;
          }
          return Math.min(times * 50, 2000);
        },
        socket_keepalive: false,
        host: "localhost",
        port: 6379,
        password: "test"
      }),
 });



不错,这个有效了!对我来说,区别在于 plugins: [responseCachePlugin()] 部分。添加了这部分后,我的自定义缓存方法开始被调用。 - Zevgon

0

你应该能够通过实现自己的接口来使用NPM包'apollo-server-caching'。请参见实现自己的缓存提供的示例。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接