cache your rails app

16
Content Caching in Rails Ahmad Gozali [email protected]

Upload: achmad-gozali

Post on 18-May-2015

1.183 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Cache Your Rails App

Content Caching in Rails

Ahmad [email protected]

Page 2: Cache Your Rails App

Content Cache

• Page cache• Action cache• Fragment cache

Page 3: Cache Your Rails App

Page Cache (1)

• Easiest to use• Fastest• Worst scaling properties

Page 4: Cache Your Rails App

Page Cache (2)

• Pages created by Rails as normal• Written out to public directory• Cached pages served directly by webserver without involking rails

Page 5: Cache Your Rails App

Enable Page Caching

class PostsController < ApplicationController caches_page :show cache_sweeper :posts_sweeper, :only => [:create, :update, :destroy]

def show Post.find_by_id(params[:id]) end

end

Page 6: Cache Your Rails App

Sweepers

Rails::Initializer.run do |config| # ... config.load_paths += %W( #{RAILS_ROOT}/app/sweepers ) # ...end

Page 7: Cache Your Rails App

Expires Cache

class PostsSweeper < ActionController::Caching::Sweeper observe Post def after_update(post) expire_cache_for(post) end ...

Page 8: Cache Your Rails App

.htaccess

RewriteRule ^$ index.html [QSA]RewriteRule ^([^.]+)$ $1.html [QSA]RewriteCond %{REQUEST_FILENAME} !-fRewriteRule ^(.*)$ dispatch.fcgi [QSA,L]

Page 9: Cache Your Rails App

Action Caching

• Similar to page cache, but runs entirely inside of Rails• Slower, because Rails is always involved• Much less complex on the web server side; no mod_rewrite tricks• Uses the fragment cache internally

Page 10: Cache Your Rails App

Example

class PostsController < ApplicationController layout 'base' before_filter :authenticate caches_action :list, :show

Page 11: Cache Your Rails App

Cleanup Action Cache

expire_action(:controller => 'posts', :action => 'list') expire_action(:controller => 'posts', :action => 'show', :id => record.id)

Page 12: Cache Your Rails App

Fragment Cache

• You have to call it yourself, because it works on short bits of data, not whole pages.• read_fragment(key) and write_fragment(key,value)• Expire with expire_fragment(key) (or regex).• No way to list entries.

Page 13: Cache Your Rails App

Example<strong>My Blog Posts</strong><% cache do %> <ul> <% for post in @posts %> <li><%= link_to post.title, :controller => 'posts', :action => 'show', :id => post %></li> <% end %> </ul><% end %>

Page 14: Cache Your Rails App

Post Controllers

def list unless read_fragment({}) @post = Post.find(:all, :order => 'created_on desc', :limit => 10) %> endend

Page 15: Cache Your Rails App

Expire Fragment Cache

expire_fragment(:controller => 'post', :action => 'list')

Page 16: Cache Your Rails App

Demo