用memcatche代替smarty的文件缓存 转

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']
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值