Rails:根据查询结果使缓存无效

时间:2014-12-21 12:04:11

标签: ruby-on-rails activerecord memcached dalli

我的Rails应用程序中的查询不需要很长时间才能运行(~180ms),但确实会返回很多结果。结果用在API中,结果转换为JSON很昂贵(~3s)。为了加快速度,我将这样缓存:

key = 'new_prices'
query = Prices.new_this_month.where('...')
json = cache(key, expires_in: 60.minutes) do
  render_to_string json: query, each_serializer: PriceSerializer
end
render json: json

在后台,可以将新价格添加到数据库中。如何以这样的方式生成缓存密钥:如果query的结果发生更改,缓存将失效?

我使用Rails 3.2,通过dalli gem进行memcached。

1 个答案:

答案 0 :(得分:0)

由于您有new_this_month范围,我认为Prices有一个created_at时间戳。在这种情况下,您只需在缓存密钥中使用最新的created_at

cache_key = "new_prices-#{Prices.order('created_at DESC').take.created_at}"

如果你有一个好的数据库索引,这应该是一个非常快速的查询。