《PHP編程:php操作memcache緩存方法分享》要點(diǎn):
本文介紹了PHP編程:php操作memcache緩存方法分享,希望對(duì)您有用。如果有疑問,可以聯(lián)系我們。
相關(guān)主題:memcache擴(kuò)展 / 鍵值KeyValue存儲(chǔ)數(shù)據(jù)庫
使用memcache的前提是必要在服務(wù)端先配置好memcahche的環(huán)境!確認(rèn)memcahce可以正常連接之后就可以在程序使用了!PHP教程
<?php /** * Memcache緩存操作 * @author hxm * @version 1.0 * @since 2015.05.04 */ class MCache extends Object implements CacheFace { private $mem = null; //Mem對(duì)象 private $sId = 1; //servier服務(wù)ID /** * 初始化Memcache * * @return Object */ public function __construct() { if ( !class_exists('Memcache') ) { throw new QException('PHP extension does not exist: Memcache'); } $this->mem = new Memcache(); } /** * 鏈接memcahce服務(wù) * * @access private * @param string $key 關(guān)鍵字 * @param string $value 緩存內(nèi)容 * @return array */ private function connect( $sid ) { $file = $this->CacheFile(); require $file; if(! isset($cache) ) { throw new QException('緩存配置文件不存在'.$file); } $server = $cache[$this->cacheId]; $sid = isset($sid) == 0 ? $this->sId : $sid;//memcache服務(wù)選擇 if ( ! $server[$sid]) { throw new QException('當(dāng)前操作的緩存服務(wù)器配置文件不存在'); } $host = $server[$sid]['host']; $port = $server[$sid]['port']; try { $this->mem->connect( $host , $port ); } catch (Exception $e) { exit('memecache連接失敗,錯(cuò)誤信息:'. $e->getMessage()); } } /** * 寫入緩存 * * @access private * @param string $key 關(guān)鍵字 * @param string $value 緩存內(nèi)容 * @return array */ public function set( $key , $value , $sid , $expire = 0) { $data = $this->get($key , $sid); //如果已經(jīng)存在key值 if( $data ) { return $this->mem->set( $key , $value ,MEMCACHE_COMPRESSED , $expire); } else { return $this->mem->add( $key , $value ,MEMCACHE_COMPRESSED , $expire); } } /** * 讀取緩存 * * @access private * @param string $key 關(guān)鍵字 * @param int $sid 選擇第幾臺(tái)memcache服務(wù)器 * @return array */ public function get( $key , $sid) { $this->connect( $sid ); return $this->mem->get($key); } /** * 清洗(刪除)已經(jīng)存儲(chǔ)的所有的元素 * * @access private * @return array */ public function flush() { $this->connect(); return $this->mem->flush(); } /** * 刪除緩存 * * @access private * @param string $key 關(guān)鍵字 * @param int $sid 選擇第幾臺(tái)memcache服務(wù)器 * @return array */ public function remove( $key , $sid) { $this->connect(); return $this->mem->delete($key); } /** * 析構(gòu)函數(shù) * 最后關(guān)閉memcache */ public function __destruct() { /*if(! $this->mem) { $this->mem->close(); }*/ } }
以上所述便是本文的全部內(nèi)容了,希望大家能夠喜歡.PHP教程
歡迎參與《PHP編程:php操作memcache緩存方法分享》討論,分享您的想法,維易PHP學(xué)院為您提供專業(yè)教程。
轉(zhuǎn)載請注明本頁網(wǎng)址:
http://www.fzlkiss.com/jiaocheng/10407.html