常用參數(shù)
- -d 守護(hù)進(jìn)程方式啟動
- -l 127.0.0.1 地址為127.0.0.1
- -p 11211 端口
- -m 150 分配 150M 內(nèi)存
- -u root 用root身份去運(yùn)行
客戶端安裝(libmemcached、php的擴(kuò)展)
Tip: --prefix=/path/to/install_path 可以指定安裝目錄
解壓php擴(kuò)展的壓縮包之后,進(jìn)入該目錄,運(yùn)行phpize
,就會出現(xiàn)configure
文件多矮。可能報錯,需要你指定php-config
文件(/path/to/php/bin/php-config),以及l(fā)ibmemcached安裝的目錄,按照提示一步一步來再来。
make install
會返回一個擴(kuò)展的地址
編輯 php.ini:
extension=memcached.so
測試
php -m | grep memcached 查看是否安裝成功
使用
$m = new Memcached();
$array = array(
array('127.0.0.1',11211);
);
$m->addServers($array);
$m->add('mkey','mvalue',600);
//$m->add('mkey','mvalue_02',600)
// ↑ 不會替換掉原來的
$m->replace('mkey','mvalue_02',600)
// ↑ 替換掉mkey得值
$m->get('mkey');
$m->set('mkey','mvalue',600);
// ↑ 當(dāng)存在會替換,不存在會生成
$m->delete('mkey');// 刪除
$m->flush() // 清空所有
//針對 int 數(shù)據(jù)
$m->set('num',5,0); // 0 表示永久生效
$m->increment('num',5); //num 增加 5
//復(fù)合類型存儲與讀取
$data = array(
'key' => 'value',
'k2' => 'v2'
)
$m->setMulti($data,0);
$m->getMulti(array('key','key2'));
$m->deleteMulti(array('key','key2');
$m->getResultCode()
// ↑ 獲得上一次操作的編碼
$m->getResultMessage()
// ↑ 獲得上一次操作的消息
讓我們自己動手封裝一個簡單 Memcache類
//Tip: 由于時間原因,這里我并沒有進(jìn)行一些測試极颓,寫的不一定對。
//這里封裝的很簡單群嗤,目的就是熟悉一下php memcached 擴(kuò)展提供的一些方法,大家還可以自己動手封裝一個更加健壯的兵琳,用適配器模式狂秘,適配Redis等。
//類似于這樣
//set $cache->operation($key,$value,$time)
//get $cache->operation($key)
//delete $cache->operation($key,null)
Class Cache
{
private $type = 'Memacached'; //存儲使用的Cache類型
private $instance; //存儲實(shí)例
private $time = 0; //默認(rèn)存儲時間
private $error; //錯誤
// 構(gòu)造器
public function __construct(){
if(!class_exists($this->type)){
$this->error = 'No'.$this->type;
return false;
}else{
//存儲實(shí)例
$this->instance = new $this->type;
}
}
public function addServer($array){
$this->instance->addServers($array);
}
// 主要操作類
public function operation($key,$value = '',$time = NULL){
$number = func_num_args();//獲取參數(shù)個數(shù)
if($number == 1){
$this->get($key) //只有一個參數(shù)獲取操作
}else if($number >= 2 ){
//第二個參數(shù)為空代表刪除
if($value === null)
{
$this->delete($key);
return;
}
// 存儲操作
$this->set($key,$value,$time);
}
}
// 返回錯誤
public function getError()
{
// 存在本類的錯誤躯肌,就返回者春,并且終止執(zhí)行下面語句。
if($this->error) return $this->error;
// 沒有執(zhí)行上面的清女,就直接返回Memacached的上一個操作的信息
return $this->instance->getResultMessages();
}
// 存儲
public function set($key,$value,$time = NULL)
{
if($time == NULL)$this->instance->set($key,$value,$this->time);
$this->instance($key,$value,$time);
if($this->instance->getResultCode() != 0)return false;
}
public function get($key){
$result = $this->intance->get($key);
if($this->instance->getResultCode() != 0)return false;
return $result;
}
public function delete(){
$result = $this->intance->delete($key);
if($this->instance->getResultCode() != 0)return false;
return $result;
)
public function flush(){
return $this->instance->flush();
}
public function getInstance(){
if($this->instance)return $this->instance;
}
}