標籤:style blog http color 使用 os
在項目中,涉及大訪問量時,合理的使用緩衝能減輕資料庫的壓力,同時提升使用者體驗。即在非即時性的需求的前提下,一小段時間內(若干秒),用於顯示的資料從緩衝中擷取的,而不用直接讀取資料庫,能有效減少資料庫的讀取壓力。這裡記錄一下php語言使用memcache的情形:
首先,我們建立一個memcachepool,可以根據不同的配置讀取,產生不同的memcache執行個體。用到$memcache->addServer($host,$port,$flag);向串連池中添加一個memcache伺服器。程式碼範例如下
1 class memcachePool{ 2 private static $instance; 3 private $memcacheList = array(); 4 private function __construct(){ 5 6 } 7 public static function getInstance(){ 8 if(self::$instance != null) 9 return self::$instance;10 self::$instance = new memcachePool();11 return self::$instance;12 }13 /**14 * get memcache object from pool15 * @param [type] $host 伺服器16 * @param [type] $port 連接埠17 * @param [type] $flag 控制是否使用持久化串連。預設TRUE18 * @return [type]19 */20 public function getMemcache($host,$port,$flag){21 if(isset($this->memcacheList[$host.$port]))22 return $this->memcacheList[$host.$port];23 24 $memcache = new Memcache();25 // 向串連池中添加一個memcache伺服器26 $memcache->addServer($host,$port,$flag);27 //開啟大值自動壓縮,第一個參數表示處理資料大小的臨界點,第二個參數表示壓縮的比例,預設為0.228 $memcache->setCompressThreshold(2000,0.2);29 $this->memcacheList[$host.$port] = $memcache;30 return $memcache;31 }32 }View Code
接著實現一個包含memcache常用方法如add,set,get,flush,delete等的方法類,這裡命名為dlufmemcache
1 class dlufMemcache{ 2 private $memcache = null; 3 function __construct($host,$port){ 4 5 $this->memcache = memcachepool::getInstance()->getMemcache($host,$port,true); 6 } 7 /** 8 * memcache set value 9 * @param [type] $key 鍵10 * @param [type] $value 值11 * @param integer $expire 到期的時間,如果此值設定為0表明此資料永不到期12 * @param integer $flag 標誌位 使用MEMCACHE_COMPRESSED指定對值進行壓縮(使用zlib)13 * @param [type] $serializetype14 */15 public function set($key,$value,$expire=0,$flag=0,$serializetype=null){16 if($serializetype == ‘json‘ && is_array($value)){17 $value = json_encode($value);18 }19 $this->memcache->set($key,$value,$flag,$expire);20 }21 /**22 * 從服務端尋找元素23 * @param [type] $key24 * @return [type]25 */26 public function get($key){27 return $this->memcache->get($key);28 }29 /**30 * 增加一個條目到快取服務器31 * @param [type] $key32 * @param [type] $value33 * @param integer $expire34 * @param integer $flag35 * @param [type] $serializetype36 */37 public function add($key,$value,$expire=0,$flag=0,$serializetype=null){38 if($serializetype == ‘json‘ && is_array($value)){39 $value = json_encode($value);40 }41 $ret = $this->memcache->add($key,$value,$flag,$expire);42 return $ret;43 }44 /**45 * 清洗(刪除)已經儲存的所有的元素46 * @return [type]47 */48 public function flush(){49 return $this->memcache->flush();50 }51 /**52 * 從服務端刪除一個元素53 * @param [type] delete 參數:key要刪除的元素的key 刪除該元素的執行時間 timeout如果值為0,則該元素立即刪除。54 * @return [type]55 */56 public function delete($key){57 $ret = $this->memcache->delete($key,0);58 return $ret;59 }60 }View Code
然後調用dlufmemcache:
1 $memcache = new dlufMemcache(‘127.0.0.1‘,11211);2 $memcache->set(‘memcache‘,‘come on dluf&baidu !!!!!!‘);3 $ret = $memcache->get(‘memcache‘);4 echo print_r($ret,true);
運行輸出可見:
http://php.net/manual/zh/class.memcache.php