PHP記憶體緩衝Memcached類代碼_PHP教程

來源:互聯網
上載者:User
PHP記憶體緩衝Memcached類有需要的朋友可參考一下。
代碼如下 複製代碼


class MemcacheModel {
private $mc = null;
/**
* 構造方法,用於添加伺服器並建立memcahced對象
*/
function __construct(){
$params = func_get_args();
$mc = new Memcache;
//如果有多個memcache伺服器
if( count($params) > 1){
foreach ($params as $v){
call_user_func_array(array($mc, 'addServer'), $v);
}
//如果只有一個memcache伺服器
} else {
call_user_func_array(array($mc, 'addServer'), $params[0]);
}
$this->mc=$mc;
}
/**
* 擷取memcached對象
* @return object memcached對象
*/
function getMem(){
return $this->mc;
}
/**
* 檢查mem是否串連成功
* @return bool 串連成功返回true,否則返回false
*/
function mem_connect_error(){
$stats=$this->mc->getStats();
if(empty($stats)){
return false;
}else{
return true;
}
}

private function addKey($tabName, $key){
$keys=$this->mc->get($tabName);
if(empty($keys)){
$keys=array();
}
//如果key不存在,就添加一個
if(!in_array($key, $keys)) {
$keys[]=$key; //將新的key添加到本表的keys中
$this->mc->set($tabName, $keys, MEMCACHE_COMPRESSED, 0);
return true; //不存在返回true
}else{
return false; //存在返回false
}
}
/**
* 向memcache中添加資料
* @param string $tabName 需要快取資料表的表名
* @param string $sql 使用sql作為memcache的key
* @param mixed $data 需要緩衝的資料
*/
function addCache($tabName, $sql, $data){
$key=md5($sql);
//如果不存在
if($this->addKey($tabName, $key)){
$this->mc->set($key, $data, MEMCACHE_COMPRESSED, 0);
}
}
/**
* 擷取memcahce中儲存的資料
* @param string $sql 使用SQL的key
* @return mixed 返回緩衝中的資料
*/
function getCache($sql){
$key=md5($sql);
return $this->mc->get($key);
}


/**
* 刪除和同一個表相關的所有緩衝
* @param string $tabName 資料表的表名
*/
function delCache($tabName){
$keys=$this->mc->get($tabName);
//刪除同一個表的所有緩衝
if(!empty($keys)){
foreach($keys as $key){
$this->mc->delete($key, 0); //0 表示立刻刪除
}
}
//刪除表的所有sql的key
$this->mc->delete($tabName, 0);
}
/**
* 刪除單獨一個語句的緩衝
* @param string $sql 執行的SQL語句
*/
function delone($sql){
$key=md5($sql);
$this->mc->delete($key, 0); //0 表示立刻刪除
}
}


http://www.bkjia.com/PHPjc/444667.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/444667.htmlTechArticlePHP記憶體緩衝Memcached類有需要的朋友可參考一下。 代碼如下 複製代碼 ?PHP class MemcacheModel { private $mc = null; /** * 構造方法,用於添加伺服器並創...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.