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

 

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

[php] view plaincopy
 
  1. <?php  
  2.   
  3. //页面业务逻辑处理,获得结果  
  4. $objPage = new Page_IndexModel($arrParams);  
  5.   
  6. //一系列的业务逻辑放在了objPage中,调用process方法获得结果集  
  7. $arrResult = $objPage->process();  
  8.   
  9. //获得结果后smarty赋值  
  10. $smarty->assign($arrResult);  
  11.   
  12. //输出模板  
  13. $smarty->display();  
  14.   
  15. ?>  


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


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

原文地址:https://www.cnblogs.com/xxcn/p/4385473.html