首先,我們建立一個memcachepool,可以根據不同的配置讀取,生成不同的memcache實例。用到$memcache- addServer($host,$port,$flag);向連接池中添加一個memcache服務器。代碼示例如下:
html' target='_blank'>class memcachePool{ private static $instance; private $memcacheList = array(); private function __construct(){ public static function getInstance(){ if(self::$instance != null) return self::$instance; self::$instance = new memcachePool(); return self::$instance; * get memcache object from pool * @param [type] $host 服務器 * @param [type] $port 端口 * @param [type] $flag 控制是否使用持久化連接。默認TRUE * @return [type] public function getMemcache($host,$port,$flag){ if(isset($this- memcacheList[$host.$port])) return $this- memcacheList[$host.$port]; $memcache = new Memcache(); // 向連接池中添加一個memcache服務器 $memcache- addServer($host,$port,$flag); //開啟大值自動壓縮,第一個參數表示處理數據大小的臨界點,第二個參數表示壓縮的比例,默認為0.2 $memcache- setCompressThreshold(2000,0.2); $this- memcacheList[$host.$port] = $memcache; return $memcache; }
接著實現一個包含memcache常用方法如add,set,get,flush,delete等的方法類,這里命名為dlufmemcache
class dlufMemcache{ private $memcache = null; function __construct($host,$port){ $this- memcache = memcachepool::getInstance()- getMemcache($host,$port,true); * memcache set value * @param [type] $key 鍵 * @param [type] $value 值 * @param integer $expire 到期的時間,如果此值設置為0表明此數據永不過期 * @param integer $flag 標志位 使用MEMCACHE_COMPRESSED指定對值進行壓縮(使用zlib) * @param [type] $serializetype public function set($key,$value,$expire=0,$flag=0,$serializetype=null){ if($serializetype == json is_array($value)){ $value = json_encode($value); $this- memcache- set($key,$value,$flag,$expire); * 從服務端查找元素 * @param [type] $key * @return [type] public function get($key){ return $this- memcache- get($key); * 增加一個條目到緩存服務器 * @param [type] $key * @param [type] $value * @param integer $expire * @param integer $flag * @param [type] $serializetype public function add($key,$value,$expire=0,$flag=0,$serializetype=null){ if($serializetype == json is_array($value)){ $value = json_encode($value); $ret = $this- memcache- add($key,$value,$flag,$expire); return $ret; * 清洗(刪除)已經存儲的所有的元素 * @return [type] public function flush(){ return $this- memcache- flush(); * 從服務端刪除一個元素 * @param [type] delete 參數:key要刪除的元素的key 刪除該元素的執行時間 timeout如果值為0,則該元素立即刪除。 * @return [type] public function delete($key){ $ret = $this- memcache- delete($key,0); return $ret; }
然后調用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);
運行輸出可見:
想了解更多關于PHP的知識不?那就趕緊去關注PHP 的PHP視頻教程吧!
以上就是PHP調用MEMCACHE高速緩存技術實例的詳細內容,PHP教程
鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。
新聞熱點
疑難解答