PHP通过文件存储来实现缓存

时间:2023-03-08 23:57:33
PHP通过文件存储来实现缓存
在一些数据库数据记录较大,但是服务器有限的时候,可能一条MySQL查询就会好几百毫秒,一个简单的页面一般也有十几条查询,这个时候也个页面加载下来基本要好几秒了,如果并发量高的话服务器基本就瘫痪了,造成一个页面很久也加载不下来,这个时候我们可以使用文件缓存来缓解下MySQL的压力,下面给个使用例子。
  1. <?php
  2. //页面业务逻辑处理,获得结果
  3. $objPage = new Page_IndexModel($arrParams);
  4. //一系列的业务逻辑放在了objPage中,调用process方法获得结果集
  5. $arrResult = $objPage->process();
  6. //获得结果后smarty赋值
  7. $smarty->assign($arrResult);
  8. //输出模板
  9. $smarty->display();
  10. ?>

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

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

参考来源: 
PHP通过文件存储来实现缓存
http://www.lai18.com/content/407149.html