【问题标题】:How to cache using apollo-server如何使用 apollo-server 进行缓存
【发布时间】:2019-02-03 15:48:53
【问题描述】:

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 资源管理器时,我的缓存函数都不会被调用。

我尝试过使用 cacheControl : truecacheControl 设置,就像在 https://medium.com/brikl-engineering/serverless-graphql-cached-in-redis-with-apollo-server-2-0-f491695cac7f 中一样。什么都没有。

有没有不使用付费 Apollo Engine 系统在 Apollo 中实现基本缓存的示例?

【问题讨论】:

  • 你有 Redis 服务器吗?为了能够提供 chached 响应,您将需要 Redis Servermemcached server,因为包需要 localhost 或 host: 'redis-server' 上的另一台服务器上的主机 IP 地址,其中 redis-server 是 IP 地址。
  • 请将答案标记为已接受

标签: graphql apollo apollo-server


【解决方案1】:

您应该能够通过实现自己的接口来使用 NPM 包“apollo-server-caching”。请参阅Implementing Your Own Cache,它提供了一个示例。

【讨论】:

    【解决方案2】:

    你可以看看这个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"
          }),
     });
    
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-25
      • 2021-08-18
      • 2018-04-19
      • 2018-11-21
      • 2019-03-26
      • 2020-09-25
      • 2019-12-16
      • 2020-04-22
      相关资源
      最近更新 更多