rails低级缓存不适用于活动记录

wrrgggsh  于 2021-06-09  发布在  Redis
关注(0)|答案(1)|浏览(330)

我在用 graphql 我的rails api。使用 redis 用于缓存存储。
在graphql查询中,我使用缓存优化性能:
graphql/types/query\类型.rb

field :labels, [Types::LabelType], null: false do
  description 'Get all food labels'
end

def labels
  Rails.cache.fetch("labels", expires_in: 24.hours) do
    Label.all
  end
end

在数据库中植入10个标签,当我在中测试查询时 localhost:3000/graphiql ,正确显示了10个结果。但是,如果在数据库中手动删除一行,它将返回9条记录,而不是缓存的10条结果。
以下是我的环境配置:
配置/environments/development.rb

if Rails.root.join('tmp', 'caching-dev.txt').exist?
  config.action_controller.perform_caching = true
  config.cache_store = :redis_cache_store, { url: ENV.fetch("REDIS_URL_CACHING", "redis://localhost:6379/0") }
  config.public_file_server.headers = {
    'Cache-Control' => "public, max-age=#{2.days.to_i}"
  }
else
  config.action_controller.perform_caching = false
  config.cache_store = :null_store
end

我跑了 rails dev:cache 而且有 caching-dev.txttmp 目录。我错过了什么?

e0uiprwp

e0uiprwp1#

我发现了类似的问题并尝试了他们的答案。建议的解决方案有:
负荷模型: Label.all.load (rails 5.2.1-模型和片段缓存)
将它们转换为数组: Label.to_a (Rails4中的低级缓存)
将结果存储到局部变量: labels = Label.all (rails 4低级缓存不工作)
第一个和第二个工作正常。
graphql/types/query\类型.rb

def labels
  Rails.cache.fetch("labels", expires_in: 24.hours) do
    Label.all.load
  end
end

提示:每当您更改缓存块时,在rails控制台中运行rails.cache.clear

问题是它是块 Label.all 是缓存的,不是结果。
无论我如何更改块,它已经被缓存,所以结果不会被缓存。
我跑了 Rails cache clear 在rails控制台中,它工作正常。

相关问题