Home  >  Article  >  Backend Development  >  PHP基于文件存储实现缓存的方法_php技巧

PHP基于文件存储实现缓存的方法_php技巧

WBOY
WBOYOriginal
2016-05-16 20:10:35937browse

本文实例讲述了PHP基于文件存储实现缓存的方法。分享给大家供大家参考。具体如下:

在一些数据库数据记录较大,但是服务器有限的时候,可能一条MySQL查询就会好几百毫秒,一个简单的页面一般也有十几条查询,这个时候也个页面加载下来基本要好几秒了,如果并发量高的话服务器基本就瘫痪了,造成一个页面很久也加载不下来,这个时候我们可以使用文件缓存来缓解下MySQL的压力,下面给个使用例子。

<&#63;php
//页面业务逻辑处理,获得结果
$objPage = new Page_IndexModel($arrParams);
//一系列的业务逻辑放在了objPage中,调用process方法获得结果集
$arrResult = $objPage->process();
//获得结果后smarty赋值
$smarty->assign($arrResult);
//输出模板
$smarty->display();
&#63;>

现在我们用文件缓存来略过Page业务处理这一步

<&#63;php
$cachFile = './index.php';
//缓存文件存在且时间不超过一小时,则直接使用缓存的结果集,不在进行任何的MySQL查询了
if(file_exists($cacheFile) && time()-filemtime($cachFile) < 3600) {
  //使用缓存中的结果
  $arrResult = include($cachFile);
} else {
  $objPage = new Page_IndexModel($arrParams);
  $arrResult = $objPage->process();
  $strContent = "<&#63;php \n return ".var_export($arrResult, true)."\n;";
  //将结果集缓存
  file_put_contents($cachFile, $strContent);
}
//获得结果后smarty赋值
$smarty->assign($arrResult);
//输出模板
$smarty->display();

希望本文所述对大家的php程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn