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節點下所有數據  
 

 

 

 

 


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