首先,我们建立一个memcachepool,可以根据不同的配置读取,生成不同的memcache实例。用到$memcache->addServer($host,$port,$flag);向连接池中添加一个memcache服务器。代码示例如下:
class memcachePool{ private static $instance; private $memcacheList = array(); private function __construct(){ } public static function getInstance(){ if(self::$instance != null) return self::$instance; self::$instance = new memcachePool(); return self::$instance; } public function getMemcache($host,$port,$flag){ if(isset($this->memcacheList[$host.$port])) return $this->memcacheList[$host.$port]; $memcache = new Memcache(); // 向连接池中添加一个memcache服务器 $memcache->addServer($host,$port,$flag); //开启大值自动压缩,第一个参数表示处理数据大小的临界点,第二个参数表示压缩的比例,默认为0.2 $memcache->setCompressThreshold(2000,0.2); $this->memcacheList[$host.$port] = $memcache; return $memcache; } }
接着实现一个包含memcache常用方法如add,set,get,flush,delete等的方法类,这里命名为dlufmemcache
class dlufMemcache{ private $memcache = null; function __construct($host,$port){ $this->memcache = memcachepool::getInstance()->getMemcache($host,$port,true); } public function set($key,$value,$expire=0,$flag=0,$serializetype=null){ if($serializetype == 'json' && is_array($value)){ $value = json_encode($value); } $this->memcache->set($key,$value,$flag,$expire); } public function get($key){ return $this->memcache->get($key); } public function add($key,$value,$expire=0,$flag=0,$serializetype=null){ if($serializetype == 'json' && is_array($value)){ $value = json_encode($value); } $ret = $this->memcache->add($key,$value,$flag,$expire); return $ret; } public function flush(){ return $this->memcache->flush(); } public function delete($key){ $ret = $this->memcache->delete($key,0); return $ret; } }
然后调用dlufmemcache:
1 $memcache = new dlufMemcache('127.0.0.1',11211); 2 $memcache->set('memcache','come on dluf&baidu !!!!!!'); 3 $ret = $memcache->get('memcache'); 4 echo print_r($ret,true);
运行输出可见:
想了解更多关于PHP的知识不?那就赶紧去关注PHP中文网的PHP视频教程吧!
以上就是PHP调用MEMCACHE高速缓存技术实例的详细内容,更多请关注其它相关文章!