Rails Caching DB Queries and Best Practices

后端 未结 4 1370
小蘑菇
小蘑菇 2021-01-31 04:23

The DB load on my site is getting really high so it is time for me to cache common queries that are being called 1000s of times an hour where the results are not changing. So f

4条回答
  •  没有蜡笔的小新
    2021-01-31 04:47

    I would go ahead and take a look at Memoization, which is now in Rails 2.2.

    "Memoization is a pattern of initializing a method once and then stashing its value away for repeat use."

    There was a great Railscast episode on it recently that should get you up and running nicely.

    Quick code sample from the Railscast:

    class Product < ActiveRecord::Base
      extend ActiveSupport::Memoizable
    
      belongs_to :category
    
      def filesize(num = 1)
        # some expensive operation
        sleep 2
        12345789 * num
      end
      memoize :filesize
    end
    

    More on Memoization

提交回复
热议问题