title: What's the simplest way to get a dump of all memcached keys into a file?
body: <p>This is from just a single memcached server with around 20M keys (no expiry) and around 2G of data.</p>
  
  <p>What's the easiest way to get a dump of all the key/value pairs into a flat file? I first looked at the java net.spy.memcached.MemcachedClient, but this client does not support getting all keys (I think). If I had a list of all keys (which I don't), I could easily use this client to get all of the values.</p>
  
  <p>I know I can get all keys using some telnet commands (e.g., telnet localhost 11211; stats items; stats cachedump  ), but it's not clear to me how to automate this robustly.</p>
  
  <p>EDIT: Here's what I did to get this working on a toy memcached server on my machine. It seems to work but I only put two keys in memcached, so hopefully this method will scale ok:</p>
  
  <p>shell commands:</p>
  
  <pre><code>sudo yum install memcached
  sudo /etc/init.d/memcached restart # maybe unnecessary
  sudo yum install php
  sudo yum install php-pecl-memcache
  sudo service httpd reload
  </code></pre>
  
  <p>php script, based on <a href="http://100days.de/serendipity/archives/55-Dumping-MemcacheD-Content-Keys-with-PHP.html">this</a>:</p>
  
  <pre><code>&lt;?php
  $memcache = new Memcache();
  $memcache-&gt;connect('127.0.0.1', 11211) or die ("Could not connect");
  $list = array();
  $allSlabs = $memcache-&gt;getExtendedStats('slabs');
  $items = $memcache-&gt;getExtendedStats('items');
  foreach($allSlabs as $server =&gt; $slabs) {
      foreach($slabs AS $slabId =&gt; $slabMeta) {
          if (!is_int($slabId)) {
              continue;
          }
          $cdump = $memcache-&gt;getExtendedStats('cachedump', (int) $slabId, 100000000);
          foreach($cdump AS $server =&gt; $entries) {
              if ($entries) {
                  foreach($entries AS $eName =&gt; $eData) {
                      print_r($eName);
                      print_r(":");
                      $val = $memcache-&gt;get($eName);
                      print_r($val);
                      print_r("\n");
                  }
              }
          }
      }
  }
  ?&gt;
  </code></pre>
  
  <p>EDIT2: The above script does not seem to return all of the mappings. If I insert the line <code>count($entries)</code>, it only returns a little over 50k, even with the limit parameter set to 100M, but executing <code>stats items</code> from telnet shows over 5M entries. Does anyone know why this might be the case?</p>
  
  <p>EDIT3: This <a href="http://code.google.com/p/memcached/wiki/NewProgrammingFAQ">link</a> suggests that cachedump doesn't get all keys from memcached. I've hit a limit of around 50k keys that are returned either by cachedump, this PHP script, or a perl script similar to one in the link provided by Zach Bonham. Is there any way around this?</p>