這篇文章主要介紹了PHP如何調用MEMCACHE高速緩存技術,具有一定借鑒價值,需要的朋友可以參考下。希望大家閱讀完這篇文章后大有收獲。下面讓小編帶著大家一起了解一下。
在項目中,涉及大訪問量時,合理的使用緩存能減輕數據庫的壓力,同時提升用戶體驗。即在非實時性的需求的前提下,一小段時間內(若干秒),用于顯示的數據從緩存中獲取的,而不用直接讀取數據庫,能有效的減少數據庫的讀取壓力。這里記錄一下php語言使用memcache的情形:
首先,我們建立一個memcachepool,可以根據不同的配置讀取,生成不同的memcache實例。用到$memcache->addServer($host,$port,$flag);向連接池中添加一個memcache服務器。代碼示例如下:
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如何調用MEMCACHE高速緩存技術內容對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,遇到問題就找億速云,詳細的解決方法等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。