(2010-08-13 23:18:24)
标签: memcache smarty 集群 缓存 it 分类: 雕虫小技
smarty可以通过cache_handler_func更改缓存方式,具体例子可以先看看官网:http://www.smarty.net/manual/en/section.template.cache.handler.func.php
官网的例子是用mysql方式,可以修改一下,改为用memcache的方式进行缓存,代码如下:
function memcache_handler($action, &$smarty_obj, &$cache_content, $tpl_file=null, $cache_id=null, $compile_id=null, $exp_time=null)
{
$use_gzip = false;
// create unique cache id
$CacheID = md5($tpl_file.$cache_id.$compile_id);
$memcache = new Memcache;
$memcache->addServer('192.168.56.201',11211); //根据你实际的memcache集群设定
$memcache->addServer('192.168.56.202',11211);
$memcache->addServer('192.168.56.203',11211);
$memcache->addServer('192.168.56.204',11211);
switch ($action) {
case 'read':
// get cache from memcache
$getContents = $memcache->get($CacheID);
if(!$getContents) {
$smarty_obj->trigger_error("memcache_handler: get failed.");
}
if($use_gzip && function_exists("gzuncompress")) {
$cache_contents = gzuncompress($getContents);
} else {
$cache_contents = $getContents;
}
$return = $getContents;
break;
case 'write':
// save cache to memcache
if($use_gzip && function_exists("gzcompress")) {
// compress the contents for storage efficiency
$contents = gzcompress($cache_content);
} else {
$contents = $cache_content;
}
$writeContents = $memcache->set($CacheID,$contents);
if(!$writeContents) {
$smarty_obj->trigger_error("memcache_handler: set failed.");
}
$return = $writeContents;
break;
case 'clear':
// clear cache info
if(empty($cache_id) && empty($compile_id) && empty($tpl_file)) {
// clear them all
$clearCache = $memcache->flush();
} else {
$clearCache = $memcache->delete($cache_id);
}
if(!$clearCache) {
$smarty_obj->trigger_error("memcache_handler: clear failed.");
}
$return = $clearCache;
break;
default:
// error, unknown action
$smarty_obj->trigger_error("cache_handler: unknown action \"$action\"");
$return = false;
break;
}
return $return;
}
值得注意的是:smarty2.6.x用cache_handler_func后有一个问题,不论是mysql或者是memcache或者是其他等,无论设定lifetime多长,程序每次运行都会更新cache,未达到缓存效果,不知是否smarty的bug,查看了一下smarty的源代码,发现读缓存的那个函数里没有返回缓存内容,因此程序未命中内容,所以会执行写缓存操作,导致每次都更新缓存,解决方法是打开core.read_cache_file.php的37行修改为:
$params['results'] = call_user_func_array($smarty->cache_handler_func,
array('read', &$smarty, &$params['results'], $params['tpl_file'], $params['cache_id'], $params['compile_id']
来源:http://blog.sina.com.cn/s/blog_554fae310100krr7.html