1.如何使用
首先配置文件里要加上这些
'DATA_CACHE_TYPE' => 'Memcache',
'MEMCACHE_HOST' => 'tcp://127.0.0.1:11211',
'DATA_CACHE_TIME' => '10',
指定使用缓存是memcache, 这里设置的缓存过期时间是10秒,实际根据项目需要。
然后就是控制器里。首先来看看没加缓存之前:
$msgsmodel=M('message');
$count = $msgsmodel->where("content!=''")->count();
$Page = new \Think\Page($count,5);
$show = $Page->show();
$list = $msgsmodel->where("content!=''")->order('mid desc')->limit($Page->firstRow.','.$Page->listRows)->select();
foreach($list as $key => $value){
$list[$key]['addtime'] = date("Y-m-d H:i:s",$value['addtime']);
}
$this->assign('list',$list);
$this->assign('page',$show);
$this->display('/index');
exit();
下面是加入缓存功能后的修改:
$Cache = new \Think\Cache\Driver\Memcache();
$cahce_key=md5('index_datas');
$cache_key_page=md5('index_shows');
if(!$Cache->get($cahce_key)){
$count = $msgsmodel->where("content!=''")->count();
$Page = new \Think\Page($count,5);
$show = $Page->show();
$list = $msgsmodel->where("content!=''")->order('mid desc')->limit($Page->firstRow.','.$Page->listRows)->select();
foreach($list as $key => $value){
$list[$key]['addtime'] = date("Y-m-d H:i:s",$value['addtime']);
}
$Cache->add($cahce_key,serialize($list),0,10);
$Cache->add($cache_key_page,serialize($show),0,10);
//echo 'db';
}else{
//echo 'mem';
$list=unserialize($Cache->get($cahce_key));
$show=unserialize($Cache->get($cache_key_page));
}
$this->assign('list',$list);
$this->assign('page',$show);
$this->display('/index');
首先获取实例是必须的
$Cache = new \Think\Cache\Driver\Memcache();
然后帮缓存起个名字
$cahce_key=md5('index_datas');
$cache_key_page=md5('index_shows');
再就是判断是否拿到缓存,拿不到就取数据库。
$list=unserialize($Cache->get($cahce_key));
就是这样简单!
2.参考
http://blog.csdn.net/zhao0829wang/article/details/44537975
http://blog.csdn.net/pingd/article/details/50241239
3.memcahce 启动(winddows)
memcached.exe -d start
memcached.exe -d install
http://blog.csdn.net/yuhui_fish/article/details/7762299