Memcache是PHP开发中较常用到的缓存方法,在高并发的系统中是必不可少的组成部分。
- <?php
- class MyCache
- {
- private $mmc = null;
- private $group = null;
- private $version = 1;
- function __construct($group){
- if(!class_exists('mmcache')){
- $this->mmc = false;
- return;
- }
- $this->mmc = new memcache();
- $this->mmc->addServer('192.168.1.5', 11211);
- $this->mmc->addServer('192.168.1.6', 11211);
- $this->group = $group;
- $this->version = $this->mmc->get('version_'.$group);
- }
- function set($key, $var, $expire=3600){
- if(!$this->mmc)return;
- return $this->mmc->set($this->group.'_'.$this->version.'_'.$key, $var, $expire);
- }
- function get($key){
- if(!$this->mmc)return;
- return $this->mmc->get($this->group.'_'.$this->version.'_'.$key);
- }
- function incr($key, $value=1){
- if(!$this->mmc)return;
- return $this->mmc->increment($this->group.'_'.$this->version.'_'.$key, $value);
- }
- function decr($key, $value=1){
- if(!$this->mmc)return;
- return $this->mmc->decrement($this->group.'_'.$this->version.'_'.$key, $value);
- }
- function delete($key){
- if(!$this->mmc)return;
- return $this->mmc->delete($this->group.'_'.$this->version.'_'.$key);
- }
- function flush(){
- if(!$this->mmc)return;
- ++$this->version;
- $this->mmc->set('version_'.$this->group, $this->version);
- }
- }
- ?>
- // 引入定义
- include('MyCache.php');
- // 实例化
- $mc = new MyCache('abc'); // 要有域
- // 设置值
- $mc->set('word', 'hello world', 900);
- // 取得值
- echo $mc->get('word');
- // 删除值
- $mc->delete('word');
- echo $mc->get('word');
- $mc->set('counter', 1, 290000);
- echo $mc->get('counter');
- // 增加值
- $mc->incr('counter');
- $mc->incr('counter');
- echo $mc->get('counter');
- // 减少值
- $mc->decr('counter');
- echo $mc->get('counter');
- // 按组删
- $mc->flush();
















