【问题标题】:Data deleted from db but still exists in redis cache从 db 中删除的数据,但仍然存在于 redis 缓存中
【发布时间】:2018-04-27 19:54:51
【问题描述】:

我正在尝试在我的 rails 应用程序上缓存模型。 我有一个模型片段。我第一次创建记录时,会创建一个 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 中的一条记录,但它仍然出现在索引页面上。我的问题是如何同时删除数据库记录和缓存记录。

redis 助手

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

【问题讨论】:

    标签: ruby-on-rails redis


    【解决方案1】:

    从上面共享的代码 sn-p 看来,您似乎只有在使用回调将数据保存到数据库时才清除缓存。

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

    after_destroy :clear_cache.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-20
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 2015-11-21
      • 1970-01-01
      相关资源
      最近更新 更多