gpt4 book ai didi

ruby-on-rails - Rails.cache 在每次 rake 任务运行后丢弃

转载 作者:太空宇宙 更新时间:2023-11-03 16:15:38 24 4
gpt4 key购买 nike

我遇到了一个简单的问题:我的抽佣任务是:

namespace :common do
desc 'check rails cache'
task easy_task: :environment do
l = -> (test_param) do
puts "cache value isn't found, reload..."
'this is result'
end
result = Rails.cache.fetch('test_task', expires_in: 1.hour) do
l.call(1)
end
end
end

我的期望 - 输出短语“找不到缓存值,重新加载...”将仅输出 rake common:easy_task 的第一次运行,但在每次运行时都会输出。

此外,我正在尝试:

rake common:easy_task
rails common:easy_task
bundle exec spring rake common:easy_task
bundle exec spring rails common:easy_task

也没有这些帮助。

Rails 缓存在 rake 任务中不起作用,但在控制台和应用程序中起作用。为什么?

最佳答案

如果事情在控制台中工作但在 rake 任务中不工作,您可能正在使用 ActiveSupport::Cache::MemoryStore (这是 config/environments/development.rb 中的默认设置,如果你有启用缓存的临时文件,否则它使用 ActiveSupport::Cache::NullStore ,这在任何地方都不起作用,原因很明显),它将东西存储在进程内存中:

A cache store implementation which stores everything into memory in the same process.

Rails.configuration.cache_store # => :memory_store
l = -> (test_param) do
puts "cache value isn't found, reload..."
'this is result'
end
Rails.cache.fetch('test_task', expires_in: 1.hour) do
l.call(1)
end
# cache value isn't found, reload...
# => "this is result"
Rails.cache.fetch('test_task', expires_in: 1.hour) do
l.call(1)
end
# => "this is result"

但在每次使用单独进程的 rake 任务中效果不佳

$ rake common:easy_task
# [:memory_store, "pid = 26230"]
# cache value isn't found, reload...
$ rake common:easy_task
# [:memory_store, "pid = 26253"]
# cache value isn't found, reload...

即使使用 spring,每次运行的过程也是不同的

$ bin/rake common:easy_task
# Running via Spring preloader in process 26283
# [:memory_store, "pid = 26283"]
# cache value isn't found, reload...
$ bin/rake common:easy_task
# Running via Spring preloader in process 26297
# [:memory_store, "pid = 26297"]
# cache value isn't found, reload...

为了解决这个问题,我们需要使用不同的内存存储(我将使用 ActiveSupport::Cache::FileStore 用于此示例,但可以使用您喜欢的其他任何一个)

config.cache_store = :file_store, Rails.root.join('tmp/cache_store')

然后 rake 任务按预期工作:

$ bin/rake common:easy_task
# Running via Spring preloader in process 26400
# [:file_store, #<Pathname:.../tmp/cache_store>, "pid = 26400"]
# cache value isn't found, reload...
$ bin/rake common:easy_task
# Running via Spring preloader in process 26414
# [:file_store, #<Pathname:.../tmp/cache_store>, "pid = 26414"]
$ bin/rails c
# Running via Spring preloader in process 26430
result = Rails.cache.fetch('test_task', expires_in: 1.hour) do
l.call(1)
end
# => "this is result"

关于ruby-on-rails - Rails.cache 在每次 rake 任务运行后丢弃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45277992/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com