CakeFest 2024: The Official CakePHP Conference

通读缓存回调

通读缓存回调在一个元素没有从服务端检索到的时候被调用。这个回调函数会接收到 Memcached 对象,请求的 key 以及 一个引用方式传递的值变量等三个参数。此回调函数负责通过返回 true 或 false 来决定在 key 没有值时设置一个默认值。 如果回调返回 true,Memcached 会存储"传出参数"(引用传递的值变量)存储的值到 memcached 服务端并将其返回到原来 的调用函数中。仅仅 Memcached::get()Memcached::getByKey() 支持这类回调,因为 Memcache 协议不支持在请求多个 key 时提供未检索到 key 的信息。

示例 #1 通读回调示例

<?php
$m
= new Memcached();
$m->addServer('localhost', 11211);

$profile_info = $m->get('user:'.$user_id, 'user_info_cb');

function
user_info_cb($memc, $key, &$value)
{
$user_id = substr($key, 5);
/* 从数据库读取个人信息 */
/* ... */
$value = $profile_info;
return
true;
}
?>
add a note

User Contributed Notes 2 notes

up
2
chadkouse
12 years ago
Or just set the value within the callback with your own custom expiration time and return false. I think it's cleaner.
up
1
oorza2k5 at gmail dot com
15 years ago
This isn't specified anywhere, so I had a gander at the source...

The expiry on read-through cache set values is set to 0, or forever. This means if you want your key to implicitly expire, don't use the callback methods, instead check for boolean false as a return and manually set the value, at least for now.
To Top