缓存与过期键

5
我正在开发一个混搭网站,希望限制抓取源网站的次数。我只需要一个整数,想要定义一个到期时间来缓存它。
为了澄清,我只想缓存整数,而不是整个页面源代码。
是否有Ruby或Rails功能或gem可以为我完成这项工作?
2个回答

10

是的,有ActiveSupport::Cache::Store

一个抽象的缓存存储类。有多种缓存存储实现,每个实现都有自己的附加功能。请参见ActiveSupport :: Cache模块下的类,例如ActiveSupport :: Cache :: MemCacheStore。目前,MemCacheStore是大型生产网站中最流行的缓存存储。

某些实现可能不支持除获取、写入、读取、存在性和删除等基本缓存方法之外的所有方法。

ActiveSupport :: Cache :: Store可以存储任何可序列化的Ruby对象。

http://api.rubyonrails.org/classes/ActiveSupport/Cache/Store.html

cache = ActiveSupport::Cache::MemoryStore.new
cache.read('Chicago')   # => nil 
cache.write('Chicago', 2707000)
cache.read('Chicago')   # => 2707000

关于过期时间,这可以通过将时间作为初始化参数传递来实现

cache = ActiveSupport::Cache::MemoryStore.new(expires_in: 5.minutes)

如果您想使用不同的过期时间缓存一个值,写入缓存时也可以设置它。

cache.write(key, value, expires_in: 1.minute) # Set a lower value for one entry

3
请参见Rails缓存,尤其是ActiveSupport::Cache::Store:expires_in选项。
例如,您可以这样做:
value = Rails.cache.fetch('key', expires_in: 1.hour) do
    expensive_operation_to_compute_value()
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接