- 論壇徽章:
- 0
|
我們經(jīng)常會(huì)使用Memcached的存儲(chǔ)過(guò)期功能,而實(shí)際上在過(guò)期后,Memcached并不能馬上回收過(guò)期內(nèi)容,這樣會(huì)很快存滿(mǎn)至配置限制,根據(jù)不同配置,Memcached會(huì)采用LRU算法刪除緩存內(nèi)容或使用時(shí)刪除過(guò)期內(nèi)容,而有時(shí)Memcached這樣的釋放內(nèi)存的機(jī)制并不能滿(mǎn)足所有應(yīng)用,故我們?cè)赑HP基礎(chǔ)上實(shí)現(xiàn)了統(tǒng)一刪除過(guò)期內(nèi)容的功能,適用于定時(shí)清理.
- <?php
- /**
- * mem_dtor:對(duì)Memcached的過(guò)期內(nèi)存回收
- * Author:lajabs
- */
- class mem_dtor extends Memcache
- {
- private $server_id;
- public function __construct($host,$port)
- {
- $this->server_id = "$host:$port";
- $this->connect($host,$port);
- }
- // 回收所有過(guò)期的內(nèi)存
- public function gc()
- {
- $t = time();
- $_this = $this;
- $func = function($key,$info) use ($t,$_this)
- {
- if($info[1] - $t < -30) //30秒過(guò)期的緩沖
- {
- $_this->delete($key);
- }
- };
- $this->lists($func);
- }
- // 查看所有緩存內(nèi)容的信息
- public function info()
- {
- $t = time();
- $func = function($key,$info) use ($t)
- {
- echo $key,' => Exp:',$info[1] - $t,"\n"; //查看緩存對(duì)象的剩余過(guò)期時(shí)間
- };
- $this->lists($func);
- }
- private function lists($func)
- {
- $sid = $this->server_id;
- $items = $this->getExtendedStats('items'); //獲取memcached狀態(tài)
- foreach($items[$sid]['items'] as $slab_id => $slab) //獲取指定server id 的 所有Slab
- {
- $item = $this->getExtendedStats('cachedump',$slab_id,0); //遍歷所有Slab
- foreach($item[$sid] as $key => $info) //獲取Slab中緩存對(duì)象信息
- {
- $func($key,$info);
- }
- }
- }
- }
- $mem = new mem_dtor('127.0.0.1',11211);
- $mem->info();//查看狀態(tài)
- $mem->gc(); //回收
- ?>
復(fù)制代碼 |
|