mod_memcached

mod_memcached 在 memcached 服务器上缓存内容

lookup 尝试查找与键关联的数据,如果找到,则将其作为 HTTP 正文和 200 状态码返回。
store 将一个 HTTP 正文(由另一个后端生成)存储到 memcached 中。

缓存总是需要您思考想要缓存什么;您不能缓存随每个请求而变化的内容!

因此,大多数情况下,您可能希望为 memcached 中存储的内容设置一个 TTL;您的用户可能不需要在下一秒就获取到新内容,也许 60 秒的 TTL 仍然是可接受的(对于聊天显然不是这样……)。

另一种方法是在您的动态后端中清除键;您也可以从后端设置 memcached 内容,这可能比 memcached.store 更快。

如果键的长度超过 255 字节或包含超出 0x21 - 0x7e 范围的字符,我们将改用其哈希值(目前是 sha1,但可能会改变)。

memcached.lookup (操作)

在 memcached 数据库中搜索内容

memcached.lookup (options, action-hit, action-miss);
选项
一个包含以下条目的键值表
服务器
套接字地址(字符串形式) (默认值: 127.0.0.1:11211)
标头
(布尔值,暂不支持) 是否也查找标头。如果为 false,内容类型由 request.uri.path 决定 (默认值: false)
查找键的模式 (默认值: "%{req.path}")
命中操作
缓存命中时要运行的操作 (查找成功)
未命中操作
缓存未命中时要运行的操作 (查找未成功)

memcached.store (操作)

将生成的响应存储在 memcached 数据库中

memcached.store options;
选项
一个包含以下条目的键值表
服务器
套接字地址(字符串形式) (默认值: 127.0.0.1:11211)
标志
(整数) 存储数据的标志 (默认值 0)
TTL
存储的 TTL (默认值 30;如果要“永远”缓存,请使用 0)
最大大小
我们想要存储的最大字节大小 (默认值: 64*1024)
标头
(布尔值,暂不支持) 是否也存储标头 (默认值: false)
存储键的模式 (默认值: "%{req.path}")

示例

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 也向每个 worker 的 luaState 导出 Lua API (用于 lua.handler)

memcached.new(address) 创建一个新连接;一个连接提供

  • req = con:get(key, cb | vr)
  • req = con:set(key, value, cb | vr, [ttl])
  • con:setq(key, value, [ttl])

如果提供了回调函数,该回调函数将带有一个响应对象被调用;否则,当准备就绪时,响应将在 req.response 中。

响应对象包含

  • code: 1 – 成功, 2 – 未存储, 3 – 已存在, 4 – 未找到, 5 – 错误
  • error: 错误消息
  • key: 查找键
  • 标志
  • TTL
  • cas
  • 数据