本文章給大家分享一個PHP清除Memcache過期緩存程序代碼,Memcached會采用LRU算法刪除緩存內容或使用時刪除過期內容,而有時Memcached這樣的釋放內存的機制并不能滿足所有應用,故我們在PHP基礎上實現了統一刪除過期內容的功能,適用于定時清理.
PHP實例代碼如下:
- /**
- * Memcached的過期內存回收
- */
- class mem_dtor extends Memcache
- {
- private $server_id;
- public function __construct($host,$port)
- {
- $this->server_id = "$host:$port";
- $this->connect($host,$port);
- }
- // 回收所有過期的內存
- public function gc()
- {
- $t = time();
- $_this = $this;
- $func = function($key,$info) use ($t,$_this)
- {
- if($info[1] - $t delete($key);
- }
- };
- $this->lists($func);
- }
- // 查看所有緩存內容的信息
- 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狀態
- 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();//查看狀態
- $mem->gc(); //回收
新聞熱點
疑難解答