最近在項目中由於要防止併發,須要使用php的memcached擴展,memcached擴展支持cas協議,而memcache擴展卻不支持。安裝memcached過程當中發現windows下並無該擴展,爲了保持代碼的一致,就寫了一個既支持memcached又支持memcache的類,這樣就不用擔憂生產和本地開發代碼的不一致。(注:筆者日常工做在windows下開發,生產環境是Linux。若是你日常開發和生產環境都是linux或mac的話就不會有這個問題)php
下面就直接貼出代碼了:linux
<?phpwindows
class ZMemcached併發
{memcached
static private $mem;spa
//簡單的單例模式,減小資源消耗orm
static public function getinstance()server
{ci
if(self::$mem==null)資源
{
//判斷php是否安裝了memcached擴展
if(class_exists('Memcached'))
{
self::$mem = new Memcached();
}
else
{
self::$mem = new Memcache();
}
}
return self::$mem;
}
static public function get($key)
{
global $INI;
if(class_exists('Memcached'))
{
$m1 = self::getinstance();
//這裏能夠添加多個memecache server
$m1->addServer($INI['memcachehost'], $INI['memcacheport']);
$res['value'] = $m1->get($key, null, $cas);
$res['cas'] = $cas;
}
else
{
$m1 = self::getinstance();
$m1->addServer($INI['memcachehost'], $INI['memcacheport']);
$res['value'] = $m1->get($key);
}
return $res;
}
static public function set($key,$value,$cas)
{
$value = (string)$value;
global $INI;
if(class_exists('Memcached'))
{
$m1 = self::getinstance();
$m1->addServer($INI['memcachehost'], $INI['memcacheport']);
$res = $m1->cas($cas,$key,$value);
}
else
{
$m1 = self::getinstance();
$m1->addServer($INI['memcachehost'], $INI['memcacheport']);
$res = $m1->set($key,$value);
}
return $res;
}
}