最近在项目中因为要防止并发,需要使用php的memcached扩展,memcached扩展支持cas协议,而memcache扩展却不支持。安装memcached过程中发现windows下并没有该扩展,为了保持代码的一致,就写了
<?php //访问博客了解更多 http://back.zhizhi123.com/?p=143 class ZMemcached { static private $mem; //简单的单例模式,减少资源消耗 static public function getinstance() { 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; } }