Memcache is a very simple, distributed memory cache used widely with mysql and other databases. Often we want to inspect what is in memcache server on development environment. Here are some handy command which can be used in development environment. It may not be suitable for production environment with huge data. This article assumes that you have memcached running on local machine (Linux or Mac).
Create some test keys
This step is optional. We’ll create some test keys (600 seconds expiry). You can skip this if you already have data in memcache and don’t want to add test data to it.
$ printf "%04g\n" {1..5} | xargs -I % printf "set tmpkey% 0 600 12\r\ntmpvalue%\r\n" | nc localhost 11211 STORED STORED STORED ...
Dumping slabs
Use the following commands to list all items which will give us all slabs.
$ MEMCHOST=localhost; printf "stats items\n" | nc $MEMCHOST 11211
For printing total number of keys (from all slabs)
$ MEMCHOST=localhost; printf "stats items\n" | nc $MEMCHOST 11211 | grep ":number" | awk '{print $3}' | awk '{SUM+=$1} END {print SUM}'
For printing exact slab ids
$ MEMCHOST=localhost; printf "stats items\n" | nc $MEMCHOST 11211 | grep ":number" | awk -F":" '{print $2}'
Dumping all keys using slabs
Run the following command to dump upto 10000 keys values from all slabs. You can change 10000 to a higher value if needed. This also prints the expiry timestamp of the key. Note that in case if key never expires its value if less than memcache server start time (current time – up_time).
$ MEMCHOST=localhost; printf "stats items\n" | nc $MEMCHOST 11211 | grep ":number" | awk -F":" '{print $2}' | xargs -I % printf "stats cachedump % 10000\r\n" | nc $MEMCHOST 11211 ITEM tmpkey0005 [12 b; 1438189134 s] ITEM tmpkey0004 [12 b; 1438189134 s] ITEM tmpkey0003 [12 b; 1438189134 s] ITEM tmpkey0002 [12 b; 1438189134 s] ITEM tmpkey0001 [12 b; 1438189134 s] END
Use 0 for dumping all keys (use with caution).
$ MEMCHOST=localhost; printf "stats items\n" | nc $MEMCHOST 11211 | grep ":number" | awk -F":" '{print $2}' | xargs -I % printf "stats cachedump % 0\r\n" | nc $MEMCHOST 11211
Dumping all keys and values using slabs
Run the following command to dump values along with keys using slabs.
$ MEMCHOST=localhost; printf "stats items\n" | nc $MEMCHOST 11211 | grep ":number" | awk -F":" '{print $2}' | xargs -I % printf "stats cachedump % 0\r\n" | nc $MEMCHOST 11211 | grep ITEM | awk '{print $2}' | sed -e 's/"/\\"/g'| xargs -I % printf "get %\r\n" | nc $MEMCHOST 11211