PHP常见缓存技术 (转载)

转载地址 http://justcoding.iteye.com/blog/650010

在大部份情况下我们的网站都会使用数据库作为站点数据存储的容器。当你执行一个SQL查询时,典型的处理过程 是:连接数据库->准备SQL查询->发送查询到数据库->取得数据库返回结果->关闭数据库连接。但数据库中有些数据是完全静 态的或不太经常变动的,缓存系统会通过把SQL查询的结果缓存到一个更快的存储系统中存储,从而避免频繁操作数据库而很大程度上提高了程序执行时间,而且 缓存查询结果也允许你后期处理。

  普遍使用的缓 存技术

  数据缓存:这里所说的数据缓存是指数据库查询缓存,每次访问页面的时候,都会先检测相应的缓存数据是否存 在,如果不存在,就连接数据库,得到数据,并把查询结果序列化后保存到文件中,以后同样的查询结果就直接从缓存文件中获得。

  页面缓存:

  每次访问页面的时候,都会先检测相应的缓存页面文件是否存在,如果不存在,就连接数据库,得到数据,显示 页面并同时生成缓存页面文件,这样下次访问的时候页面文件就发挥作用了。(模板引擎和网上常见的一些缓存类通常有此功能)

  内存缓存:

  在里就不介绍了,不是本文所要讨论的,只简单提一下:

  Memcached是高性能的,分布式的内存对象缓存系统,用于在动态应用中减少数据库负载,提升访问速 度。

  dbcached 是一款基于 Memcached 和 NMDB 的分布式 key-value 数据库内存缓存系统。

  以上的缓存技术虽然能很好的解决频繁查询数据库的问题,但其缺点在在于数据无时效性,下面我给出我在项目 中常用的方法:

  时间触发缓 存:

  检查文件是否存在并且时间戳小于设置的过期时间,如果文件修改的时间戳比当前时间戳减去过期时间戳大,那 么就用缓存,否则更新缓存。

  设定时间内不去判断数据是否要更新,过了设定时间再更新缓存。以上只适合对时效性要求不高的情况下使用 ,否则请看下面。

  内容触发缓 存:

  当插入数据或更新数据时,强制更新缓存。

  在这里我们可以看到,当有大量数据频繁需要更新时,最后都要涉及磁盘读写操作。怎么解决呢?我在日常项目 中,通常并不缓存所有内容,而是缓存一部分不经常变的内容来解决。但在大负荷的情况下,最好要用共享内存做缓存系统。

  到这里PHP缓存也许有点解决方案了,但其缺点是,因为每次请求仍然要经过PHP解析,在大负荷的情况下 效率问题还是比效严重,在这种情况下,也许会用到静态缓存。

  静态缓存

  这里所说的静态缓存是指HTML缓存,HTML缓存一般是无需判断数据是否要更新的,因为通常在使用 HTML的场合一般是不经常变动内容的页面。数据更新的时候把HTML也强制更新一下就可以了。

 

 

 

 

实例1:

 

 

Php代码  收藏代码
  1. <?php  
  2. /* 
  3.  实    例: 
  4. include("cache.php"); 
  5.   
  6. $cache = new cache(30); 
  7. $cache->cacheCheck(); 
  8.   
  9. echo date("Y-m-d H:i:s"); 
  10.   
  11. $cache->caching(); 
  12. */  
  13. class cache {  
  14.   // 缓存目录  
  15.   var $cacheRoot        = "./cache/";  
  16.   //缓存更新时间秒数,0为不缓存  
  17.   var $cacheLimitTime   = 0;  
  18.   //缓存文件名  
  19.   var $cacheFileName    = "";  
  20.   //缓存扩展名  
  21.   var $cacheFileExt     = "php";  
  22.    
  23.   /* 
  24.    * 构造函数 
  25.    * int $cacheLimitTime 缓存更新时间 
  26.    */  
  27.   function cache( $cacheLimitTime ) {  
  28.     ifintval$cacheLimitTime ) )  
  29.       $this->cacheLimitTime = $cacheLimitTime;  
  30.     $this->cacheFileName = $this->getCacheFileName();  
  31.     ob_start();  
  32.   }  
  33.    
  34.   /* 
  35.    * 检查缓存文件是否在设置更新时间之内 
  36.    * 返回:如果在更新时间之内则返回文件内容,反之则返回失败 
  37.    */  
  38.   function cacheCheck(){  
  39.     iffile_exists$this->cacheFileName ) ) {  
  40.       $cTime = $this->getFileCreateTime( $this->cacheFileName );  
  41.       if$cTime + $this->cacheLimitTime > time() ) {  
  42.         echo file_get_contents$this->cacheFileName );  
  43.         ob_end_flush();  
  44.         exit;  
  45.       }  
  46.     }  
  47.     return false;  
  48.   }  
  49.    
  50.   /* 
  51.    * 缓存文件或者输出静态 
  52.    * string $staticFileName 静态文件名(含相对路径) 
  53.    */  
  54.   function caching( $staticFileName = "" ){  
  55.     if$this->cacheFileName ) {  
  56.       $cacheContent = ob_get_contents();  
  57.       //echo $cacheContent;  
  58.       ob_end_flush();  
  59.    
  60.       if$staticFileName ) {  
  61.           $this->saveFile( $staticFileName$cacheContent );  
  62.       }  
  63.    
  64.       if$this->cacheLimitTime )  
  65.         $this->saveFile( $this->cacheFileName, $cacheContent );  
  66.     }  
  67.   }  
  68.    
  69.   /* 
  70.    * 清除缓存文件 
  71.    * string $fileName 指定文件名(含函数)或者all(全部) 
  72.    * 返回:清除成功返回true,反之返回false 
  73.    */  
  74.   function clearCache( $fileName = "all" ) {  
  75.     if$fileName != "all" ) {  
  76.       $fileName = $this->cacheRoot . strtoupper(md5($fileName)).".".$this->cacheFileExt;  
  77.       iffile_exists$fileName ) ) {  
  78.         return @unlink( $fileName );  
  79.       }else return false;  
  80.     }  
  81.     if ( is_dir$this->cacheRoot ) ) {  
  82.       if ( $dir = @opendir( $this->cacheRoot ) ) {  
  83.         while ( $file = @readdir( $dir ) ) {  
  84.           $check = is_dir$file );  
  85.           if ( !$check )  
  86.           @unlink( $this->cacheRoot . $file );  
  87.         }  
  88.         @closedir$dir );  
  89.         return true;  
  90.       }else{  
  91.         return false;  
  92.       }  
  93.     }else{  
  94.       return false;  
  95.     }  
  96.   }  
  97.    
  98.   /* 
  99.    * 根据当前动态文件生成缓存文件名 
  100.    */  
  101.   function getCacheFileName() {  
  102.     return  $this->cacheRoot . strtoupper(md5($_SERVER["REQUEST_URI"])).".".$this->cacheFileExt;  
  103.   }  
  104.    
  105.   /* 
  106.    * 缓存文件建立时间 
  107.    * string $fileName   缓存文件名(含相对路径) 
  108.    * 返回:文件生成时间秒数,文件不存在返回0 
  109.    */  
  110.   function getFileCreateTime( $fileName ) {  
  111.     if( ! trim($fileName) ) return 0;  
  112.    
  113.     iffile_exists$fileName ) ) {  
  114.       return intval(filemtime$fileName ));  
  115.     }else return 0;  
  116.   }  
  117.    
  118.   /* 
  119.    * 保存文件 
  120.    * string $fileName  文件名(含相对路径) 
  121.    * string $text      文件内容 
  122.    * 返回:成功返回ture,失败返回false 
  123.    */  
  124.   function saveFile($fileName$text) {  
  125.     if( ! $fileName || ! $text ) return false;  
  126.    
  127.     if$this->makeDir( dirname( $fileName ) ) ) {  
  128.       if$fp = fopen$fileName"w" ) ) {  
  129.         if( @fwrite( $fp$text ) ) {  
  130.           fclose($fp);  
  131.           return true;  
  132.         }else {  
  133.           fclose($fp);  
  134.           return false;  
  135.         }  
  136.       }  
  137.     }  
  138.     return false;  
  139.   }  
  140.    
  141.   /* 
  142.    * 连续建目录 
  143.    * string $dir 目录字符串 
  144.    * int $mode   权限数字 
  145.    * 返回:顺利创建或者全部已建返回true,其它方式返回false 
  146.    */  
  147.   function makeDir( $dir$mode = "0777" ) {  
  148.     if( ! $dir ) return 0;  
  149.     $dir = str_replace"\\", "/", $dir );  
  150.       
  151.     $mdir = "";  
  152.     foreachexplode"/"$dir ) as $val ) {  
  153.       $mdir .= $val."/";  
  154.       if$val == ".." || $val == "." || trim( $val ) == "" ) continue;  
  155.         
  156.       if( ! file_exists$mdir ) ) {  
  157.         if(!@mkdir$mdir$mode )){  
  158.          return false;  
  159.         }  
  160.       }  
  161.     }  
  162.     return true;  
  163.   }  
  164. }  
  165.   
  166.   
  167. $cache = new cache(30);  
  168. $cache->cacheCheck();  
  169.    
  170. echo date("Y-m-d H:i:s");  
  171.    
  172. $cache->caching();  
  173.   
  174. ?>  
 

 

实例2: 数据缓存

 

Php代码  收藏代码
  1. <?php  
  2.   
  3. class Cache {  
  4.   
  5.     private $dir = 'cache';  
  6.     private $expiration = 3600;  
  7.   
  8.     function __construct($dir = '')  
  9.     {  
  10.         if(!emptyempty($dir)){ $this->dir = $dir; }  
  11.     }  
  12.   
  13.     private function _name($key)  
  14.     {  
  15.         return sprintf("%s/%s"$this->dir, sha1($key));  
  16.     }  
  17.   
  18.     public function get($key$expiration = '')  
  19.     {  
  20.   
  21.         if ( !is_dir($this->dir) OR !is_writable($this->dir))  
  22.         {  
  23.             return FALSE;  
  24.         }  
  25.   
  26.         $cache_path = $this->_name($key);  
  27.   
  28.         if (!@file_exists($cache_path))  
  29.         {  
  30.             return FALSE;  
  31.         }  
  32.   
  33.         $expiration = emptyempty($expiration) ? $this->expiration : $expiration;  
  34.   
  35.         if (filemtime($cache_path) < (time() - $expiration))  
  36.         {  
  37.             $this->clear($key);  
  38.             return FALSE;  
  39.         }  
  40.   
  41.         if (!$fp = @fopen($cache_path'rb'))  
  42.         {  
  43.             return FALSE;  
  44.         }  
  45.   
  46.         flock($fp, LOCK_SH);  
  47.   
  48.         $cache = '';  
  49.   
  50.         if (filesize($cache_path) > 0)  
  51.         {  
  52.             $cache = unserialize(fread($fpfilesize($cache_path)));  
  53.         }  
  54.         else  
  55.         {  
  56.             $cache = NULL;  
  57.         }  
  58.   
  59.         flock($fp, LOCK_UN);  
  60.         fclose($fp);  
  61.   
  62.         return $cache;  
  63.     }  
  64.   
  65.     public function set($key$data)  
  66.     {  
  67.   
  68.         if ( !is_dir($this->dir) OR !is_writable($this->dir))  
  69.         {  
  70.              $this->_makeDir($this->dir);  
  71.         }  
  72.   
  73.         $cache_path = $this->_name($key);  
  74.   
  75.         if ( ! $fp = fopen($cache_path'wb'))  
  76.         {  
  77.             return FALSE;  
  78.         }  
  79.   
  80.         if (flock($fp, LOCK_EX))  
  81.         {  
  82.             fwrite($fp, serialize($data));  
  83.             flock($fp, LOCK_UN);  
  84.         }  
  85.         else  
  86.         {  
  87.             return FALSE;  
  88.         }  
  89.         fclose($fp);  
  90.         @chmod($cache_path, 0777);  
  91.         return TRUE;  
  92.     }  
  93.   
  94.     public function clear($key)  
  95.     {  
  96.         $cache_path = $this->_name($key);  
  97.   
  98.         if (file_exists($cache_path))  
  99.         {  
  100.             unlink($cache_path);  
  101.             return TRUE;  
  102.         }  
  103.   
  104.         return FALSE;  
  105.     }  
  106.   
  107.     public function clearAll()  
  108.     {  
  109.         $dir = $this->dir;  
  110.         if (is_dir($dir))   
  111.         {  
  112.             $dh=opendir($dir);  
  113.   
  114.             while (false !== ( $file = readdir ($dh)))   
  115.             {  
  116.   
  117.                 if($file!="." && $file!="..")   
  118.                 {   
  119.                     $fullpath=$dir."/".$file;  
  120.                     if(!is_dir($fullpath)) {  
  121.                         unlink($fullpath);  
  122.                     } else {  
  123.                         delfile($fullpath);  
  124.                     }  
  125.                 }  
  126.             }  
  127.             closedir($dh);  
  128.             // rmdir($dir);  
  129.         }  
  130.   }  
  131.   
  132.    private function _makeDir( $dir$mode = "0777" ) {  
  133.         if( ! $dir ) return 0;  
  134.         $dir = str_replace"\\", "/", $dir );  
  135.       
  136.         $mdir = "";  
  137.         foreachexplode"/"$dir ) as $val ) {  
  138.           $mdir .= $val."/";  
  139.           if$val == ".." || $val == "." || trim( $val ) == "" ) continue;  
  140.             
  141.           if( ! file_exists$mdir ) ) {  
  142.             if(!@mkdir$mdir$mode )){  
  143.              return false;  
  144.             }  
  145.           }  
  146.         }  
  147.         return true;  
  148.     }  
  149. }  
 

例子:

 

Java代码  收藏代码
  1. <?  
  2. require_once('cache.php');  
  3.   
  4. $cache = new Cache();  
  5.   
  6. $data = $cache->get('key');  
  7.   
  8. if ($data === FALSE)  
  9. {  
  10.     $data = 'This will be cached';  
  11.     $cache->set('key', $data);  
  12.     echo $data.'--first time';  
  13. }  
  14.       
  15. echo $data;  
  16.   
  17. //$cache->clearAll();  
  18. //$cache->clear('key');  
  19.   
  20. //Do something with $data  
 

 

另一个数据缓存:

 

Php代码  收藏代码
  1. <?php  
  2. class file_cache  
  3. {  
  4.     private $root_dir;  
  5.       
  6.     public function __construct ($root_dir)  
  7.     {  
  8.         $this->root_dir = $root_dir;  
  9.           
  10.         if (FALSE == file_exists($this->root_dir))  
  11.         {  
  12.             mkdir($this->root_dir, 0700, true);  
  13.         }  
  14.     }  
  15.       
  16.     public function set ($key$value)  
  17.     {  
  18.         $key = $this->escape_key($key);  
  19.           
  20.         $file_name = $this->root_dir . '/' . $key;  
  21.           
  22.         $dir = dirname($file_name);  
  23.           
  24.         if (FALSE == file_exists($dir))  
  25.         {  
  26.             mkdir($dir, 0700, true);  
  27.         }  
  28.           
  29.         file_put_contents($file_name, serialize($value), LOCK_EX);  
  30.     }  
  31.       
  32.     public function get ($key)  
  33.     {  
  34.         $key = $this->escape_key($key);  
  35.           
  36.         $file_name = $this->root_dir . '/' . $key;  
  37.           
  38.         if (file_exists($file_name))  
  39.         {  
  40.             return unserialize(file_get_contents($file_name));  
  41.         }  
  42.           
  43.         return null;  
  44.     }  
  45.       
  46.     public function remove ($key)  
  47.     {  
  48.         $key = $this->escape_key($key);  
  49.           
  50.         $file = $this->root_dir . '/' . $key;  
  51.           
  52.         if (file_exists($file))  
  53.         {  
  54.             unlink($file);  
  55.         }  
  56.     }  
  57.       
  58.     public function remove_by_search ($key)  
  59.     {  
  60.         $key = $this->escape_key($key);  
  61.           
  62.         $dir = $this->root_dir . '/' . $key;  
  63.           
  64.         if (strrpos($key'/') < 0)  
  65.             $key .= '/';  
  66.           
  67.         if (file_exists($dir))  
  68.         {  
  69.             $this->removeDir($dir);  
  70.         }  
  71.     }  
  72.       
  73.     private function escape_key ($key)  
  74.     {  
  75.         return str_replace('..'''$key);  
  76.     }  
  77.       
  78.     function removeDir($dirName)  
  79.     {  
  80.         $result = false;  
  81.           
  82.         $handle = opendir($dirName);  
  83.           
  84.         while(($file = readdir($handle)) !== false)  
  85.         {  
  86.             if($file != '.' && $file != '..')  
  87.             {  
  88.                 $dir = $dirName . DIRECTORY_SEPARATOR . $file;  
  89.               
  90.                 is_dir($dir) ? $this->removeDir($dir) : unlink($dir);  
  91.             }  
  92.         }  
  93.           
  94.         closedir($handle);  
  95.           
  96.         rmdir($dirName) ? true : false;  
  97.           
  98.         return $result;  
  99.     }  
  100. }  
  101.   
  102.   
  103. $data_1 = array(  
  104.   'u_id' => 1,  
  105.   'name' => '利沙'  
  106. );  
  107.   
  108. $data_2 = array(  
  109.   'u_id' => 2,  
  110.   'name' => 'WaWa'  
  111. );  
  112.   
  113. $cache = new file_cache("test");  
  114.   
  115. $cache->set("user/1/data"$data_1);  //保存数据  
  116. $cache->set("user/2/data"$data_2);  //保存数据  
  117.   
  118. $result = $cache->get("user/1/data"); //获取数据  
  119.   
  120. echo '测试如下:<pre>';  
  121. print_r($result);  
  122.   
  123. //$cache->remove("user/1/data"); //删除数据  
  124.   
  125. //$cache->remove_by_search("user", $data_1);  //删除user节点下所有数据  
 

 

 

 

 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章