2010年1月28日 星期四

nginx , page cache, capistrano

Segregated page cache storage
Rails page caching vs nginx Restful route 可能會造成有相同的html, like index and create, 所以利用nginx 做一些檢查來避免
nginx rewrite rules with Passenger

if (-f $request_filename) {
break;
}

# cached pages
#set $cache_extension '';
#if ($request_method = GET) {
# set $cache_extension '.html';
#}

# the above is a hack because nginx doesn't allow nested or ANDed ifs
#if (-f $request_filename$cache_extension) {
# rewrite (.*) $1.html break;
#}

# 這個才有用 上面那些都沒用 orz, 用$uri 才有用
if (-f $document_root/cache/$uri/index.html) {
rewrite (.*) /cache/$1/index.html break;
}

if (-f $document_root/cache/$uri.html) {
rewrite (.*) /cache/$1.html break;
}


# everything else goes to the mongrel cluster
if (!-f $request_filename) {
proxy_pass http://mongrels;
break;
}



#In config/environments/production.rb, tell Rails to put cached pages in the public/cache directory.

config.action_controller.page_cache_directory = File.join(RAILS_ROOT, 'public', 'cache')

#In nginx.conf, set up the precedence for locating static files. First look in public for regular static files. Next look in the cache directory for an exact match for the url. Lastly, look in the cache directory for the url with .html appended. That will let you cache pages for regular URLs with no .html extension as well as ones with extensions like .xml, .atom, .json, etc.

if (-f $request_filename) {
break;
}

# if (-f /cache$request_filename) {
# rewrite (.*) /cache$1 break;
# break;
# }

# if (-f /cache$request_filename.html) {
# rewrite (.*) /cache$1.html break;
# break;
# }

#The capistrano recipes have to do a couple things. You need to create the shared/cache directory when setting up the deployment.

after "deploy:setup", "create_page_cache"
task :create_page_cache, :roles => :app do
run "umask 02 && mkdir -p #{shared_path}/cache"
end


after "deploy:update_code","symlink_shared_dirs"
task :symlink_shared_dirs, :roles => :app, :except => {:no_release => true, :no_symlink => true} do
run <<-CMD
cd #{release_path} &&
ln -nfs #{shared_path}/cache #{release_path}/public/cache
CMD
end

#When doing a deploy, the standard behavior is to flush the cache, just to be on the safe side. If you want to retain cached pages, as when making a change you know won't affect rendering, tell capistrano not to flush.

# default behavior is to flush page cache on deploy
set :flush_cache, true

# page cache management
task :keep_page_cache do
set :flush_cache, false
end

after "deploy:cleanup", "flush_page_cache"
task :flush_page_cache, :roles => :app do
if flush_cache
run <<-CMD
rm -rf #{shared_path}/cache/*
CMD
end
end

#With the above setup, you can deploy and retain the cache with the following capistrano command:
$ cap keep_page_cache deploy

沒有留言: