当缓存关闭时,变量在请求之间持久存在是否很常见?我可以关掉它吗?
我一直认为,如果我想在请求之间持久保存数据,我应该使用数据库或其他持久存储,而记忆仅用于在多次调用方法时在一个请求中保存计算。
我的型号:
应用程序/模型/simple_model.rb:
class SimpleModel < ApplicationRecord
def time
@time ||= Time.now
end
end
跨不同的http请求
@time
返回相同的值。 @time.object_id
也一样。
[1] pry(#<SimpleModel>)> @time
=> 2024-04-10 00:43:13.325467 +0200
[2] pry(#<SimpleModel>)> @time.object_id
=> 14600
# -- another request ---
[1] pry(#<SimpleModel>)> @time
=> 2024-04-10 00:43:13.325467 +0200
[2] pry(#<SimpleModel>)> @time.object_id
=> 14600
如果我重新启动服务器,那么
@time
就是新的。
我的
config/environments/development.rb
是默认的。缓存已禁用:
config.action_controller.perform_caching = false
config.cache_store = :null_store
我不使用任何特定的宝石。这几乎是带有 `
的普通 Rails我用
rails s
运行轨道。它正在开发模式下运行:
$ rails s -p 3554
=> Booting Puma
=> Rails 6.1.5 application starting in development
=> Run `bin/rails server --help` for more startup options
Puma starting in single mode...
* Puma version: 5.6.2 (ruby 3.1.3-p185) ("Birdie's Version")
* Min threads: 5
* Max threads: 5
* Environment: development
* PID: 87377
* Listening on http://127.0.0.1:3554
* Listening on http://[::1]:3554
Use Ctrl-C to stop
如果这是预期的行为,而我的理解不正确,那么在什么情况下这种情况会无效?手动干预是唯一的解决方案吗?
感谢@tadman,我发现了问题。
在我接到的一连串电话中:
class SomeAnotherModel < ApplicationRecord
def self.active
@active ||= find_by(end_at: nil)
end
end
请注意,这是一个类方法,因此它似乎是跨请求“缓存”的。