Memcached How to find keys by pattern?
When using Memcached , sometimes questions may arise: “But how to see all Memcached keys?” or "How to find all keys by mask" * "or" sql_ * "?"
Then the manuals open and the search for such a function begins , but, unfortunately, it doesn’t
turn out :-( Then Google starts ... And there isn’t much there :-(
And then the search for undocumented features starts :-) and then “Hurray! Found!”
This code just adds such a simple function as viewing keys, and returns them as an array, with which you can then do whatever you like :-)
- /**
- * getKeys()
- *
- * get all keys from Memcache
- *
- * @author Roman Kutsy
- * @version 2.0.20090708
- *
- * @return array $keys
- */
- function getKeys()
- {
- ///////////////////////////////////////////////////////////////////////
-
- $s = @fsockopen('127.0.0.1',11211);
-
- // SLABS //////////////////////////////////////////////////////////////
-
- fwrite($s, 'stats slabs'."\r\n");
-
- $slabs = array();
-
- while( !feof($s) )
- {
- $temp = fgets($s, 256);
-
- preg_match('/^STAT\s([0-9]*)(.*)/', $temp, $slab_temp);
-
- if(isset($slab_temp['1']) && strlen($slab_temp['1'])>0)
- {
- $slabs[] = $slab_temp['1'];
- }
-
- unset($slab_temp);
-
- if(trim($temp)=='END')
- {
- break;
- }
- }
-
- unset($temp);
-
- // ITEMS //////////////////////////////////////////////////////////////
-
- fwrite($s, 'stats items'."\r\n");
-
- $items = array();
-
- while( !feof($s) )
- {
- $temp = fgets($s, 256);
-
- preg_match('/^STAT\sitems\:([0-9]*)(.*)/', $temp, $item_temp);
-
- if(isset($item_temp['1']) && strlen($item_temp['1'])>0)
- {
- $items[] = $item_temp['1'];
- }
-
- unset($item_temp);
-
- if(trim($temp)=='END')
- {
- break;
- }
- }
-
- unset($temp);
-
- $slabs = array_unique($slabs);
- $items = array_unique($items);
-
- // CACHEDUMP //////////////////////////////////////////////////////////
-
- $keys = array();
-
- foreach($slabs as &$slab)
- {
- foreach($items as &$item)
- {
- fwrite($s, 'stats cachedump '.$slab.' '.$item."\r\n");
-
- while( !feof($s) )
- {
- $temp = fgets($s, 256);
-
- // ITEM cd3aec8b1dd7ef828267408e68b6d961:user_1_status [1 b; 1247043297 s]
- // or
- // ITEM sql_custom_photos_showphoto_11 [1379 b; 1247064083 s]
-
- preg_match('/^ITEM\s([a-f0-9]{32}\:)?([A-Za-z0-9\_\-\.]*)\s\[[0-9]*\sb\;\s([0-9]*)\s.*/', $temp, $key_temp);
-
- if(isset($key_temp['2']) && strlen($key_temp['2'])>0)
- {
- $keys[] = $key_temp['2'];
- }
-
- unset($key_temp);
-
- if(trim($temp)=='END')
- {
- break;
- }
- }
- }
- }
-
- unset($temp,$slabs,$items);
-
- fclose($s);
-
- ///////////////////////////////////////////////////////////////////////
-
- $keys_temp = array_unique($keys);
- unset($keys);
- asort($keys_temp);
-
- $keys = array();
- foreach($keys_temp as &$k)
- {
- $keys[] = $k;
- }
-
- return $keys;
-
- ///////////////////////////////////////////////////////////////////////
- }
Good luck,% username%!
UPD Moved to " Web-development "