【问题标题】:Apollo server-side caching: What is cache keyed on?Apollo 服务器端缓存:缓存的关键是什么?
【发布时间】:2022-06-23 18:09:53
【问题描述】:

我正在阅读documentation for Apollo server-side caching,但没有看到任何关于缓存通常如何键控的内容。

我需要的是一个缓存,它以响应中包含的对象 ID 为键,而不是以您从查询中获得的东西为键。

例如,假设下面的 Person 对象由 ID 字段唯一标识,而 hasShortHair 字段的计算成本很高,但很少更改。

type Person {
  id: String!
  hasShortHair: Boolean!
}

假设有 2 种不同的查询类型可以返回一个 Person:

getPerson(id: String!): Person!
getAllPeople: [Person!]!

理想情况下,对于具有给定 ID 的人,如果该人最近已通过 getPerson 或 getAllPeople 获取,那么我想缓存为该人计算的 hasShortHair 的值,并将该缓存用于 both getPerson 和 getAllPeople 查询返回那个人。

像下面这样设置可以实现吗? (Based on the book example in the documentation)

type Person @key(fields: "id") @cacheControl(maxAge: 30) {
  id: String!
  hasShortHair: Boolean!
}

或者缓存是否仍会按请求进行键控?

【问题讨论】:

    标签: caching graphql apollo


    【解决方案1】:

    ApolloServerPluginCacheControl 插件解析特定字段和类型的缓存注释(例如,通过 @cacheControl 指令),并据此确定特定请求的整体缓存策略。

    根据为请求计算的缓存策略,然后在响应对象上设置Cache-Control 标头。

    您可以自己查看代码on Github

    仅此而已,不涉及缓存键。

    然后由客户端或 Apollo 前面的某个缓存代理负责使用 Cache-Control 标头进行实际缓存。

    标题格式如下:

    Cache-Control: max-age=60, private
    

    max-age 根据解释所有cacheControl 提示的规则确定。

    如果您想使用 Apollo 缓存响应,可以使用 response-cache-plugin

    更多信息在这里: https://www.apollographql.com/docs/apollo-server/performance/caching/#caching-with-responsecacheplugin-advanced

    使用 response-cache 插件,您可以将整个响应缓存在 Redis 或 memcached 中。

    在这种情况下,缓存键基于请求本身,即来自插件文档:cached responses are only used for identical requests

    所以,回答你的问题:

    理想情况下,对于具有给定 ID 的人,如果该人最近已通过 > getPerson 或 getAllPeople 获取,那么我想缓存 为该人计算的 hasShortHair 的值,并使用该值 缓存返回该人的 getPerson 和 getAllPeople 查询。

    缓存是每个请求/响应,而不是每个单独解析的字段。

    如果你想缓存字段,你必须添加自己的缓存机制来做到这一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-24
      • 1970-01-01
      • 2014-12-02
      • 2015-11-04
      • 2017-03-18
      相关资源
      最近更新 更多