Posts Tagged ‘cache’

nginx conf with alternate cache dir

Monday, January 7th, 2008

Its a good idea to use an alternate cache directory in rails (in your environment.rb):

config.action_controller.page_cache_directory = RAILS_ROOT + "/public/cache/"

This makes it easier to sweep. To setup nginx to pick up from a rails alternate cache directory like public/cache, I used:

if ($http_user_agent ~* "(iPhone|iPod)") {
  rewrite ^/$ /iphone break;
  proxy_pass http://mongrel-pt;
  break;
}
 
if (-f $request_filename) {
  break;
}
 
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;
}
 
if (-f $document_root/cache/$uri) {
  rewrite (.*) /cache/$1 break;
}
 
if (!-f $request_filename) {
  proxy_pass http://mongrel-pt;
  break;
}

It was a little tricky to figure out to use the $uri variable. The first rewrite is used for iphone requests so it doesn’t get the non-iphone cached page.

Fragment Cache Store with TTL

Wednesday, February 21st, 2007

I wanted to use a fragment cache, but I didn’t want to deal with expiring it. So I just made a self-expiring cache based on a TTL.

The fragment cache store just wants 4 methods: read, write, delete, delete_matched

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Cache::MemStore

  attr_reader :ttl, :auto_expire
    
  def initialize(options = {})
    @ttl = options[:ttl] || 10.minutes
    @cache = {}
  end
    
  def expire(pattern)
    @cache.each { |key, val| delete key if key =~ pattern }
  end
  
  def read(key, options)
    delete(key, options) and return if is_expired?(key)
    return @cache[key][:content] if @cache.has_key? key
  end
  
  def write(key, content, options)
    @cache[key] = { :content => content, :created_on => Time.now }
  end
  
  def delete_matched(pattern, options)
    expire pattern
  end
  
  def delete(key, options)
    @cache.delete key
  end
  
  def is_expired?(key)
    if @cache.has_key? key
      created_on = @cache[key][:created_on]
      return Time.now > (created_on + @ttl)
    end
  end
  
end

Then in your environment.rb put:


ActionController::Base.fragment_cache_store = Cache::MemStore.new(:ttl => 10.minutes)

railsbench gave me the following results:

page request                                      total  stddev%     r/s    ms/r
with cache: /                                   7.23471   2.8012   13.82   72.35
nocache:    /                                  25.81057   0.6966    3.87  258.11