数据已从db中删除但仍存在于redis缓存中

时间:2018-04-27 11:33:06

标签: ruby-on-rails redis

我正在尝试在我的rails应用上缓存模型。 我有一个模型 Snippets 。我第一次创建记录时,会创建一个redis计数器缓存。

模型

class Snippet < ApplicationRecord
  after_save :clear_cache
  def clear_cache
    $redis.del("snippets")
  end
end

控制器

class SnippetsController < ApplicationController
  include SnippetsHelper
  def index
    @snippets = fetch_snippets
  end
  def destroy
    @snippet.destroy
    respond_to do |format|
      format.html { redirect_to snippets_url, notice: 'Snippet was successfully destroyed.' }
      format.json { head :no_content }
    end
  end
end

查看

  <td><%= link_to 'Destroy', snippet_path(snippet["id"]), method: :delete, data: { confirm: 'Are you sure?' } %></td>

因此,每次加载索引页面时,我都会加载缓存而不是db查询。 现在虽然我已经删除了db中的记录,但它仍然出现在索引页面上。我的问题是如何同时删除db记录和缓存记录。

redis helper

module SnippetsHelper
  def fetch_snippets
    snippets = $redis.get("snippets")
    if snippets.nil?
      snippets = Snippet.all.to_json
      $redis.set("snippets", snippets)
      $redis.expire("snippets", 5.hour.to_i)
    end
    JSON.load snippets
  end
end

1 个答案:

答案 0 :(得分:1)

从上面共享的代码片段看来,只有在使用回调将数据保存到数据库时才清除缓存。

但是,当从数据库中删除数据时,您还需要更新缓存。 为此,在模型中添加回调。

after_destroy :clear_cache.
相关问题