Ruby on rails 如何在Rails中缓存任意对象(基于时间)?
我读了官方指南。它说有Ruby on rails 如何在Rails中缓存任意对象(基于时间)?,ruby-on-rails,caching,memcached,redis,Ruby On Rails,Caching,Memcached,Redis,我读了官方指南。它说有页面缓存,动作缓存和片段缓存,但它们不是我想要的 我只想缓存一个对象,而不是整个页面或视图片段,如以下伪代码: def show cache @ads, :expires_in => 1.hour do @ads = Advertisement.all do end 可能吗?使用memcache或redis?检查要在redis中缓存的对象。尝试以下操作: #To cache the object Rails.cache.write('cache-ke
页面缓存
,动作缓存
和片段缓存
,但它们不是我想要的
我只想缓存一个对象,而不是整个页面或视图片段,如以下伪代码:
def show
cache @ads, :expires_in => 1.hour do
@ads = Advertisement.all
do
end
可能吗?使用memcache
或redis
?检查要在redis中缓存的对象。尝试以下操作:
#To cache the object
Rails.cache.write('cache-key', object)
#Load the object from the cache
Rails.cache.read('cache-key')
缓存对象意味着序列化(通常通过Marshal.dump/Marshal.load)。请小心,因为某些对象无法序列化。还有一些具有大型对象图(指向其他大型对象的属性和变量),序列化/取消序列化的成本很高,并且占用的空间比您预期的要大得多。例如,通过将对象序列化到redis/memcache来“缓存”
ActiveRecord
对象不是一个好主意。您是否可以对您的代码进行详细说明,或者解释一下?
Rails.cache.write(cache_key, your_value, expires_in: 10.seconds)
Rails.cache.readh(cache_key)