我正在尝试缓存序列化程序,但缓存存在问题是它会缩短响应时间。
序列化器看起来像
class FeedSerializer < ActiveModel::Serializer
cached
embed :ids
has_one :owner, include: true, serializer: UserSerializer, root: :users
has_one :post, include: true
attributes :id, :type
def cache_key
Digest::SHA1.hexadigest([object.cache_key, owner, post].join('/'))
end
end
我在课堂上添加了cache_key
class Feed
# ...some fields and class functions...
field :key, type: String
field :title, type: String
def cache_key
[ self.key, self.title ]
end
end
并在控制器中
# GET /feeds
def index
@feed = current_user.feeds.recent.includes(:owners)
render json: @feed
end
问题是这个实现会减慢控制器,尽管缓存命中......
14:03:40 web.1 | Cache read: feed_serializer/f81fef05948d17506bf0d0923aa35e593208a21c/serializable-hash
14:03:40 web.1 | Cache fetch_hit: feed_serializer/f81fef05948d17506bf0d0923aa35e593208a21c/serializable-hash
14:03:40 web.1 | Completed 200 OK in 50ms (Views: 46.9ms)
并且没有缓存实现,在 29ms ?
中返回相同的请求14:05:38 web.1 | Completed 200 OK in 29ms (Views: 26.9ms)
任何想法会出错?
object.cache_key
返回一致的缓存密钥,当某些无效属性发生更改时,该密钥无效...
序列化程序还返回一致的缓存键...并找到缓存版本。如果我将cache_key委托给对象...没有加载侧载关系(所有者,帖子)......响应不包含它们?