首页 > 开发 > PHP > 正文

PHP清除Memcache过期缓存程序代码

2024-05-04 21:58:11
字体:大 中 小
来源:转载
供稿:网友

本文章给大家分享一个PHP清除Memcache过期缓存程序代码,Memcached会采用LRU算法删除缓存内容或使用时删除过期内容,而有时Memcached这样的释放内存的机制并不能满足所有应用,故我们在PHP基础上实现了统一删除过期内容的功能,适用于定时清理.

PHP实例代码如下:

  1. /** 
  2. * Memcached的过期内存回收 
  3. */ 
  4. class mem_dtor extends Memcache 
  5. { 
  6. private $server_id; 
  7. public function __construct($host,$port) 
  8. { 
  9. $this->server_id = "$host:$port"; 
  10. $this->connect($host,$port); 
  11. } 
  12.  
  13. // 回收所有过期的内存 
  14. public function gc() 
  15. { 
  16. $t = time(); 
  17. $_this = $this; 
  18. $func = function($key,$info) use ($t,$_this) 
  19. { 
  20. if($info[1] - $t delete($key); 
  21. } 
  22. }; 
  23. $this->lists($func); 
  24. } 
  25.  
  26. // 查看所有缓存内容的信息 
  27. public function info() 
  28. { 
  29. $t = time(); 
  30. $func = function($key,$info) use ($t) 
  31. { 
  32. echo $key,' => Exp:',$info[1] - $t,"n"; //查看缓存对象的剩余过期时间 
  33. }; 
  34. $this->lists($func); 
  35. } 
  36.  
  37. private function lists($func) 
  38. { 
  39. $sid = $this->server_id; 
  40. $items = $this->getExtendedStats('items'); //获取memcached状态 
  41. foreach($items[$sid]['items'] as $slab_id => $slab) //获取指定server id 的 所有Slab 
  42. { 
  43. $item = $this->getExtendedStats('cachedump',$slab_id,0); //遍历所有Slab 
  44. foreach($item[$sid] as $key => $info) //获取Slab中缓存对象信息 
  45. { 
  46. $func($key,$info); 
  47. } 
  48. } 
  49. } 
  50. } 
  51. $mem = new mem_dtor('127.0.0.1',11211); 
  52. $mem->info();//查看状态 
  53. $mem->gc(); //回收 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表