ruby-on-rails - 缓存过期键

标签 ruby-on-rails ruby caching web-scraping mashup

我正在开发一个混搭网站,希望限制抓取次数以抓取源网站。基本上我需要一位数据,一个整数,并且想在定义的有效期内缓存它。

澄清一下,我只想缓存整数,而不是整个页面源。

是否有 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/

相关文章:

css - 在 Rails 中添加 CSS 自定义样式失败

ruby - 使用 ruby​​ gem 解析 excel "creek"

ruby - 未初始化的常量 Selenium::WebDriver::Chrome::Options (NameError)

Android Simple MediaPlayer 问题

c++ - 使用 std::ifstream 而不是文件缓存强制读取磁盘

ruby-on-rails - Rails 是无共享的还是可以单独的请求访问相同的运行时变量?

ruby-on-rails - ruby 1.9.3 UndefinedConversionError

mysql - 在给定 sql 查询的情况下转换 Rails 中的复杂查询

ruby - 如何在 Ruby 中将字符串转换为 UTF8

javascript - 当使用 javascript 更改时,浏览器是否缓存图像 src