- 論壇徽章:
- 0
|
我們經(jīng)常會使用Memcached的存儲過期功能,而實際上在過期后,Memcached并不能馬上回收過期內(nèi)容,這樣會很快存滿至配置限制,根據(jù)不同配置,Memcached會采用LRU算法刪除緩存內(nèi)容或使用時刪除過期內(nèi)容,而有時Memcached這樣的釋放內(nèi)存的機制并不能滿足所有應用,故我們在PHP基礎(chǔ)上實現(xiàn)了統(tǒng)一刪除過期內(nèi)容的功能,適用于定時清理.
- <?php
- /**
- * mem_dtor:對Memcached的過期內(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);
- }
- // 回收所有過期的內(nèi)存
- public function gc()
- {
- $t = time();
- $_this = $this;
- $func = function($key,$info) use ($t,$_this)
- {
- if($info[1] - $t < -30) //30秒過期的緩沖
- {
- $_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"; //查看緩存對象的剩余過期時間
- };
- $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中緩存對象信息
- {
- $func($key,$info);
- }
- }
- }
- }
- $mem = new mem_dtor('127.0.0.1',11211);
- $mem->info();//查看狀態(tài)
- $mem->gc(); //回收
- ?>
復制代碼 |
|