我正在编写Rails 5 JSON API。
我根据平均评分获得了返回热门 N 博客帖子的操作。为了实现较慢的响应时间,我对数据库进行了非规范化,使posts
列有average_rating
列。
我也缓存每个查询都是这样的:
# posts_controller.rb
def top
quantity = params[:quantity]
if quantity.to_i > 0
render json: {
posts: cached_top_posts(quantity)
}, status: :ok
else
render json: '', status: :unprocessable_entity
end
end
def cached_top_posts(quantity)
Rails.cache.fetch(['top', quantity], expires_in: 1.hour) do
Post.limit(quantity).as_json(only: [:title, :content, :average_rating])
end
end
(按average_rating
排序在模型本身中)
我知道这远非最佳。
虽然在请求相同数量的帖子时它会大大缩短响应时间,但如果已经缓存前1000个帖子,它将会更好缓存100个帖子,而是从缓存的1000 中获得前100个帖子。
实现这一目标的好方法是什么?
答案 0 :(得分:0)
好吧,在我度过了一个美好的夜晚之后,我想到了一个简单的结论。
这是:
# posts_controller.rb
def cached_top_posts(quantity)
data = Rails.cache.read('top_posts')
if data.nil? || data[:quantity] < quantity
data = {
:quantity => quantity,
:posts => Post.limit(quantity).as_json(only: [:title, :content, :average_rating])
}
Rails.cache.write('top_posts', data, expires_in: 1.hour)
end
data[:posts][0...quantity]
end