Class: Racknga::Middleware::Cache — racknga - ラングバ

Class: Racknga::Middleware::Cache

Inherits:
Object
  • Object
show all
Defined in:
lib/racknga/middleware/cache.rb

Overview

This is a middleware that provides page cache.

This stores page contents into a groonga database. A groonga database can access by multi process. It means that your Rack application processes can share the same cache. For example, Passenger runs your Rack application with multi processes.

Cache key is the request URL by default. It can be customized by env[Racknga::Cache::KEY]. For example, Racknga::Middleware::PerUserAgentCache and Racknga::Middleware::JSONP use it.

This only caches the following responses:

  • 200 status response.

  • text/*, */json, */xml or /+xml content type response.

Usage:

use Racnkga::Middleware::Cache, :database_path => "var/cache/db"
run YourApplication

Constant Summary

KEY =
"racknga.cache.key"
START_TIME =
"racknga.cache.start_time"

Instance Attribute Summary (collapse)

Instance Method Summary (collapse)

Constructor Details

- (Cache) initialize(application, options = {})

A new instance of Cache

Parameters:

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :database_path (String)

    the database path to be stored caches.

Raises:

  • (ArgumentError)


98
99
100
101
102
103
104
# File 'lib/racknga/middleware/cache.rb', line 98

def initialize(application, options={})
  @application = application
  @options = Utils.normalize_options(options || {})
  database_path = @options[:database_path]
  raise ArgumentError, ":database_path is missing" if database_path.nil?
  @database = CacheDatabase.new(database_path)
end

Instance Attribute Details

- (Racknga::CacheDatabase) database (readonly)

The database used by this middleware.

Returns:



94
95
96
# File 'lib/racknga/middleware/cache.rb', line 94

def database
  @database
end

Instance Method Details

- (Object) call(environment)

For Rack.



107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/racknga/middleware/cache.rb', line 107

def call(environment)
  request = Rack::Request.new(environment)
  return @application.call(environment) unless use_cache?(request)
  age = @database.configuration.age
  key = normalize_key(environment[KEY] || request.fullpath)
  environment[START_TIME] = Time.now
  cache = @database.responses
  record = cache[key]
  if record and record.age == age
    handle_request_with_cache(cache, key, age, record, request)
  else
    handle_request(cache, key, age, request)
  end
end

- (Object) close_database

close the cache database.



128
129
130
# File 'lib/racknga/middleware/cache.rb', line 128

def close_database
  @database.close_database
end

- (Object) ensure_database

ensures creating cache database.



123
124
125
# File 'lib/racknga/middleware/cache.rb', line 123

def ensure_database
  @database.ensure_database
end