[英]Caching “render json” in Rails without page caching?
I have a controller method like this, which renders an object as JSON. 我有一个像这样的控制器方法,它将对象呈现为JSON。
def show
respond_to do |format|
format.json do
render json: @my_object, serializer: MyCustomSerializer
end
end
end
Now the json generation takes at least 12 seconds, so I would like to cache this. 现在json生成至少需要12秒钟,因此我想将其缓存。 I could use HTTP caching here (with a stale? check), but that would still require other clients (browsers) to hit the slow JSON rendering the very first time.
我可以在此处使用HTTP缓存(是否过时?检查),但这仍然需要其他客户端(浏览器)才能首次实现慢速JSON呈现。
How can I cache this "render json" call? 如何缓存此“渲染json”调用?
Assuming you are using active model serializers, you can override serializable_hash
on the serializer to return a cached version, using Rails.cache.fetch
, for example: 假设您正在使用活动模型序列化器,则可以使用
Rails.cache.fetch
覆盖serializable_hash
上的serializable_hash以返回缓存的版本,例如:
def serializable_hash
Rails.cache.fetch(my_cache_key) { super }
end
Replace my_cache_key
with a cache key that will invalidate the cached JSON (probably something based on updated_at
). 将
my_cache_key
替换为将使缓存的JSON无效的缓存键(可能是基于updated_at
东西)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.