【问题标题】:How to prevent storing nil value in rails cache?如何防止在rails缓存中存储零值?
【发布时间】:2013-07-03 08:36:25
【问题描述】:

我在我的应用程序中使用 redis-store 进行缓存,如果值返回 nil,我不想获取键和值。

Rails.cache.fetch{"user_by_comment_id:#{params['comment_id']}"} do
 User.find_by_comment_id(params['comment_id'])
end

如果它返回键“user_by_comment_id:#{params['comment_id']}”的 nil,我不想将键存储在我的缓存中。帮我解决这个问题。

【问题讨论】:

  • 如果它返回 nil 则不会在缓存中写入任何内容
  • 它为 key 写入 nil。如果它返回 nil,我不想写入缓存 key。
  • 如果没有找到记录,使用抛出异常的方法怎么样(这很脏,但我看不到其他方法)
  • 另外 - 如果没有通过评论 id 找到用户,则意味着评论不属于任何人。是不是数据一致性有问题?
  • User.find_by_comment_id!(params['comment_id'])

标签: ruby-on-rails ruby-on-rails-3 caching memcached


【解决方案1】:

您可以在 Rails.cache 类中添加方法来处理您的情况(将该代码放在初始化程序中的某处):

   module ActiveSupport
   module Cache
    class Store
      def fetch_no_nil(name, options = nil)
        if block_given?
          options = merged_options(options)
          key = namespaced_key(name, options)

          cached_entry = find_cached_entry(key, name, options) unless options[:force]
          entry = handle_expired_entry(cached_entry, key, options)

          if entry
            get_entry_value(entry, name, options)
          else
            save_block_result_to_cache_if_not_nil(name, options) { |_name| yield _name }
          end
        else
          read(name, options)
        end
      end
      private
      def save_block_result_to_cache_if_not_nil(name, options)
        result = instrument(:generate, name, options) do |payload|
          yield(name)
        end
        write(name, result, options) unless result.nil?
        result
      end
    end
  end
  end

然后使用:

Rails.cache.fetch_no_nil{"user_by_comment_id:#{params['comment_id']}"} do
 User.find_by_comment_id(params['comment_id'])
end

【讨论】:

  • @Achaius 如果您觉得答案有用,请点赞,如果答案正确,请接受。这将有助于从未回答的问题列表中删除您的问题。这并不意味着接受我的答案,您可能会接受对您有用的答案。谢谢
【解决方案2】:

更新:

从 rails 6.0.0 开始,您可以在调用 Rails.cache.fetch 时提供 skip_nil: true 选项

Here

感谢Rick Suggs 指出这一点。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-20
  • 1970-01-01
  • 1970-01-01
  • 2011-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多