我正在开发一个混搭网站,希望限制抓取次数以抓取源网站。基本上我需要一位数据,一个整数,并且想在定义的有效期内缓存它。
澄清一下,我只想缓存整数,而不是整个页面源。
是否有 ruby 或 rails 功能或 gem 已经为我完成了这个?
最佳答案
是的,有ActiveSupport::Cache::Store
An abstract cache store class. There are multiple cache store implementations, each having its own additional features. See the classes under the ActiveSupport::Cache module, e.g. ActiveSupport::Cache::MemCacheStore. MemCacheStore is currently the most popular cache store for large production websites.
Some implementations may not support all methods beyond the basic cache methods of fetch, write, read, exist?, and delete.
ActiveSupport::Cache::Store can store any serializable Ruby object.
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
关于ruby-on-rails - 缓存过期键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18172569/