Rails: Scheduled task to warm up the cache?

前端 未结 4 806
暗喜
暗喜 2021-02-06 08:08

I am using the following to cache a slow loading page using memcached:

caches_action :complex_report, :expires_in => 1.day

The controller ac

4条回答
  •  无人共我
    2021-02-06 09:03

    Take a look at this gem:

    https://github.com/tommyh/preheat

    The gem is for preheating your Rails.cache.

    From the documentation: This will "preheat" all your Rails.cache.fetch calls on your homepage. It is as simple as that!

        #app/models/product.rb
        def slow_method
          Rails.cache.fetch("product-slow-method-#{self.id}") do
            sleep 15
            Time.now
          end
        end
    
        #lib/tasks/preheat.rake
        namespace :preheat do
          desc "Preheat product caches"
          task (:products => :environment) do
            Preheat.it do
              Product.all.each do |product|
                app.get(app.products_path(product)) #or you could just call product.slow_method directly, whatever makes more sense
              end
            end
          end
        end
    
        #crontab -e
        0 * * * * /path/to/rake preheat:products RAILS_ENV=production 2>&1 >> #{Rails.root}/log/preheat.log &
    

提交回复
热议问题