使用Rails 3.1.1和Herkou
我的应用程序中有1.000种产品。它们都有一个非常慢的控制器,通过片段缓存有效地解决了这个问题。虽然数据并不经常变化,但它仍然需要定期过期(我会这样做),在我的情况下,每周一次。
现在,在清除缓存的视图之后,我不希望我的用户通过一个接一个地访问产品来创建新的片段(在第一次加载时大约需要6-8秒,缓存负载需要2-3秒)。我假设我可以使用某种脚本来完成这个任务,它将一个一个地加载每个Product,从而使服务器创建这些片段。
我可以想象这件事可以通过三种方式来处理:
发布于 2012-10-30 05:52:32
我做了这个剧本,效果很好。"product.slug“是因为我安装了friendly_id。它将生成名为www.mydomain.com/productabc-123/的url-变量,由Nokogiri读取(此解决方案需要Nokogiri gem )。
请注意,在这个解决方案中,我从片段缓存切换到了动作缓存(与使用片段缓存的问题相反)。这方面的重要区别在于当我检查缓存if Rails.cache.exist?('views/www.mydomain.com/' + product.slug)时。对于fragment_caching,它应该是片段名。
require 'nokogiri'
require 'open-uri'
Product.all.each do |product|
url = 'http://www.mydomain.com/' + product.slug
begin
if Rails.cache.exist?('views/www.mydomain.com/' + product.slug)
puts url + " is already in cache"
else
doc = Nokogiri::HTML(open(url))
puts "Reads " + url
# Verifies if the caching worked. Only for trouble shooting
if Rails.cache.exist?('views/www.mydomain.com/' + product.slug)
puts "--->" + url + " is NOW in the cache"
else
puts "--->" + url + " is still not in the cache!"
end
sleep 1
end
rescue
puts 'Normal rescue of ' + url
rescue Timeout::Error
puts 'Timeout rescue of ' + url
puts 'Sleep for 5 sec'
sleep 5
retry
end
end发布于 2015-04-10 19:28:26
创建一个作为rake任务运行的脚本,或者更好的是一个工作人员,它运行并卷曲页面。当您只需调用curl时,就不需要包含宝石了。
`curl -A "CacheRefresher" #{ENV['HOSTNAME']}/api/v1/#{klass.name.underscore.pluralize}/#{id} >/dev/null 2>&1` https://stackoverflow.com/questions/12726764
复制相似问题