mod_memcached
mod_memcached caches content on memcached servers
lookup
tries to find data associated with the key, and returns it as http body with status 200 if it finds something.
store
stores a http body (generated by another backend) in memcached.
Caching always requires you to think about what you want; you cannot cache content that changes with every request!
So most of the time you probably want to set a TTL for the stored content in memcached; your users probably don’t need new content to be available the next second, perhaps 60 seconds is still good (obviously not true for a chat…).
The other way is to purge the keys in your dynamic backend; you can set the memcached content from your backend too, which probably is faster than memcached.store
.
If the key is longer than 255 bytes or contains characters outside the range 0x21 - 0x7e we will use a hash of it instead (for now sha1, but that may change).
memcached.lookup (action)
searches the content in a memcached database
memcached.lookup (options, action-hit, action-miss);
- options
- A key-value table with the following entries:
- server
- socket address as string (default: 127.0.0.1:11211)
- headers
- (boolean, not supported yet) whether to lookup headers too. if false content-type determined by request.uri.path (default: false)
- key
- pattern for lookup key (default: "%{req.path}")
- action-hit
- action to run on cache hit (lookup was successful)
- action-miss
- action to run on cache miss (lookup was not successful)
memcached.store (action)
stores the generated response in a memcached database
memcached.store options;
- options
- A key-value table with the following entries:
- server
- socket address as string (default: 127.0.0.1:11211)
- flags
- (integer) flags for storing data (default 0)
- ttl
- ttl for storing (default 30; use 0 if you want to cache "forever")
- maxsize
- maximum size in bytes we want to store (default: 64*1024)
- headers
- (boolean, not supported yet) whether to store headers too (default: false)
- key
- pattern for store key (default: "%{req.path}")
Example
setup {
module_load "mod_memcached";
}
memcached.lookup (["key" => "%{req.scheme}://%{req.host}%{req.path}"], {
header.add "X-Memcached" => "Hit";
}, {
header.add "X-Memcached" => "Miss";
docroot "/var/www";
# important: You need a content handler before memcached.store
static;
memcached.store ["key" => "%{req.scheme}://%{req.host}%{req.path}"];
});
Lua API
mod_memcached exports a Lua API to per-worker luaState
s too (for use in lua.handler):
memcached.new(address)
creates a new connection; a connection provides:
req = con:get(key, cb | vr)
req = con:set(key, value, cb | vr, [ttl])
con:setq(key, value, [ttl])
If a callback was given, the callback gets called with a response object; otherwise the response will be in req.response when ready.
The response object has:
-
code
: 1 – Ok, 2 – Not stored, 3 – Exists, 4 – Not found, 5 – Error -
error
: error message -
key
: the lookup key flags
ttl
cas
data