Back

rails 中使用cache (最简单的) ( caching in Rails for different parameters )

发布时间: 2013-03-17 06:24:00

 http://stackoverflow.com/questions/1988658/rails-action-caching-with-querystring-parameters

1. in production.rb, :

config.action_controller.perform_caching = true

2. in your controller : (will expire in 10 munites )

class UsersController < ApplicationController
   caches_action :index, :cache_path => Proc.new { |c| c.params }, :expires_in => 10.minutes
   def index
     render :text => " name is: #{params[:name]}, time.now is: #{Time.now}"
   end
end

3. stop & start your Rails server completely, and check your logs :  ( focus on the "Read fragment / Write fragment " .) 

14:29:37 INFO: Started GET "/users?name=raynor" for 127.0.0.1 at 2013-03-17 14:29:37 +0800 
14:29:37 INFO: Processing by UsersController#index as HTML 
14:29:37 INFO:   Parameters: {"name"=>"raynor"} 
14:29:37 INFO: Read fragment views/localhost:337/users?name=raynor (0.1ms) 
14:29:37 INFO:   Rendered text template (0.0ms) 
14:29:37 INFO: Write fragment views/localhost:337/users?name=raynor (2.5ms) 
14:29:37 INFO: Completed 200 OK in 6ms (Views: 0.7ms | ActiveRecord: 0.0ms) 
14:29:40 INFO:  
14:29:40 INFO:  
14:29:40 INFO: Started GET "/users?name=raynor" for 127.0.0.1 at 2013-03-17 14:29:40 +0800 
14:29:40 INFO: Processing by UsersController#index as HTML 
14:29:40 INFO:   Parameters: {"name"=>"raynor"} 
14:29:40 INFO: Read fragment views/localhost:337/users?name=raynor (0.2ms) 
14:29:40 INFO: Completed 200 OK in 2ms (ActiveRecord: 0.0ms) 

你也可以使用 mem_cache, (这样的话就不要设置  :size option,  )

# in your Gemfile
 gem 'memcache-client', '1.8.5'  

# in your production.rb
config.cache_store = :mem_cache_store, '10.103.13.96:11311', '10.103.13.97:11314'

也可以使用redis: 

config.cache_store = :redis_store, 'redis://localhost:6379'

Back