【问题标题】:Caching associations in active model serializers在活动模型序列化程序中缓存关联
【发布时间】:2014-03-13 07:49:18
【问题描述】:

目前,我有以下序列化程序:

class UserSerializer < ActiveModel::Serializer
  cached
  delegate :cache_key, to: :object
  has_many :profiles
end

class ProfileSerializer < ActiveModel::Serializer
  cached
  delegate :cache_key, to: :object
  has_many :pages
end

class PageSerializer < ActiveModel::Serializer
  cached
  delegate :cache_key, to: :object
  has_many :posts
end

由于各种原因,在序列化我的 User 模型时,我需要序列化所有关联的配置文件、页面和帖子。不幸的是,这会导致难以有效缓存的相当大的 JSON 哈希 - 我的本地 memcached 服务器只能存储大约 75 个序列化用户。有没有办法设置序列化程序,这样我就不用缓存整个用户模型 JSON 的输出,而是只缓存 JSON 的唯一部分并提交另一个缓存提取来检索相关配置文件、页面和的序列化数据帖子?

【问题讨论】:

    标签: memcached active-model-serializers


    【解决方案1】:

    我认为在ActiveModel::Serializers 内没有办法做到这一点。您可以以使代码复杂化为代价来减小缓存大小。像这样的东西会起作用:

    user_json = UserSerializer.new(@user).as_json
    user_json[:profiles] = @user.profiles.map { |profile| ProfileSerializer.new(profile).as_json }
    etc.
    

    在您的示例中,当然需要更多的嵌套。

    这不是一个很好的解决方案 - 如果您一定要返回深度嵌套的 JSON,我认为最好的短期选择是添加更多的内存缓存容量。从长远来看,这种方法可能值得重新考虑,因为一次性归还所有东西可能不可持续。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-10
      • 2017-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多