简体   繁体   English

Rails 3.2缓存不起作用

[英]Rails 3.2 cache not working

I'm using Rails.cache.write and Rails.cache.read to store some activerecord objects, but it not seems to be workinkg. 我正在使用Rails.cache.write和Rails.cache.read来存储一些activerecord对象,但似乎不是workinkg。

posts = Post.find(...)
Rails.cache.write(myKey, posts)

... next request...

foo = Rails.cache.read(myKey)

Despite variable foo is correctly filled, this generate the same sql logs. 尽管正确填充了变量foo,但仍会生成相同的sql日志。 If I change database during "...", I got news results. 如果在“ ...”期间更改数据库,则会得到新闻结果。

What could be happen? 会发生什么?

It is recommended to cache serialised data (results only), not an ActiveRecord object with its own class name and individual object id. 建议缓存序列化的数据(仅结果),而不是具有自己的类名和单个对象ID的ActiveRecord对象。

Fetch technique is also preferred 提取技术也是首选

Rails.cache.fetch(myKes) do
  Post.find(...).as_json
end 

Try this. 尝试这个。 it will expire in 30 secs. 它将在30秒后过期。

Rails.cache.fetch("posts_for_#{myKey}", expires_in: 30.seconds) do
  posts = Post.find(...)
  posts
end

put this in some kind of method and pass that method myKey and ... for posts and it should work. 将其放在某种方法中,并将该方法myKey和...传递给帖子,它应该可以工作。 it will return from cache if exists else query on it 如果存在其他查询,它将从缓存中返回

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM