在 active_model_serializers 0.10.0 上使缓存无效的推荐方法是什么?
What is the recommended approach for invalidating the cache on active_model_serializers 0.10.0?
我在序列化器级别使用缓存,它大部分都按照我想要的方式工作(例如,模型的 updated_at 更改和关联的序列化器在缓存中无效)。
但是,在某些情况下,我需要能够手动定位特定的序列化程序并使其缓存无效。例如,我们目前正在构建一个问答功能,问题序列化程序包含 last_answer_at 和 answer_count。我希望尽可能长时间地缓存问题,因为它很少更改,但是如果创建了新答案或删除了现有答案,我希望能够针对相关问题并使其缓存无效。
我对此进行了一些调查,发现您可以使用以下方法获取缓存键:
serializer = QuestionSerializer.new(self)
adapter = ActiveModelSerializers::Adapter.create(serializer)
cache_key = serializer.cache_key(adapter)
但是,这不包括缓存键的属性部分。
我希望在这里实现的是,父对象(在我的示例中是一个问题)将包含一个方法,例如:
def clear_cache
Rails.cache.clear(cache_key)
end
def cache_key
serializer = QuestionSerializer.new(self)
adapter = ActiveModelSerializers::Adapter.create(serializer)
serializer.cache_key(adapter)
end
...在我的子对象中,在创建或删除答案时调用它。
after_create :clear_parent_cache
def clear_parent_cache
question.clear_cache
end
有更好的方法吗?您能否推荐一种始终如一地获取正确缓存键的方法?
谢谢,
旦
注意:这也是 Github 存储库 (https://github.com/rails-api/active_model_serializers/issues/1816) 中的一个问题,在此发布以确保它对更广泛的受众可见。
我认为这不是 AMS 的直接问题。
有一个really nice RailsCast on this matter。只引用要点:
class Comment < ActiveRecord::Base
belongs_to :article, :touch => true
end
Adding :touch => true to the belongs_to relationship means that when a comment is created, updated or destroyed the article it belongs to is touched.
我在序列化器级别使用缓存,它大部分都按照我想要的方式工作(例如,模型的 updated_at 更改和关联的序列化器在缓存中无效)。
但是,在某些情况下,我需要能够手动定位特定的序列化程序并使其缓存无效。例如,我们目前正在构建一个问答功能,问题序列化程序包含 last_answer_at 和 answer_count。我希望尽可能长时间地缓存问题,因为它很少更改,但是如果创建了新答案或删除了现有答案,我希望能够针对相关问题并使其缓存无效。
我对此进行了一些调查,发现您可以使用以下方法获取缓存键:
serializer = QuestionSerializer.new(self)
adapter = ActiveModelSerializers::Adapter.create(serializer)
cache_key = serializer.cache_key(adapter)
但是,这不包括缓存键的属性部分。
我希望在这里实现的是,父对象(在我的示例中是一个问题)将包含一个方法,例如:
def clear_cache
Rails.cache.clear(cache_key)
end
def cache_key
serializer = QuestionSerializer.new(self)
adapter = ActiveModelSerializers::Adapter.create(serializer)
serializer.cache_key(adapter)
end
...在我的子对象中,在创建或删除答案时调用它。
after_create :clear_parent_cache
def clear_parent_cache
question.clear_cache
end
有更好的方法吗?您能否推荐一种始终如一地获取正确缓存键的方法?
谢谢, 旦
注意:这也是 Github 存储库 (https://github.com/rails-api/active_model_serializers/issues/1816) 中的一个问题,在此发布以确保它对更广泛的受众可见。
我认为这不是 AMS 的直接问题。
有一个really nice RailsCast on this matter。只引用要点:
class Comment < ActiveRecord::Base
belongs_to :article, :touch => true
end
Adding :touch => true to the belongs_to relationship means that when a comment is created, updated or destroyed the article it belongs to is touched.