Listing keys used in a memcached server

Maybe this is of no use to anybody, but it was useful to me while developing some caching code, so I hope it can be useful to someone else.

This is a script will list every key that’s being used in a memcached server.

I haven’t tried it in a production server, and you sholud be careful doing it. It looks that some of the commands are blocking and can affect the performance for the rest of the clients.

    #!/bin/bash
 
    # Script to see which keys are stored in a memcached server
    # Warning: stats command is blocking, so be careful if you want to use this in production
 
    SERVER=localhost
    PORT=11211
 
    stats=`echo -e "stats items \n quit" | nc $SERVER $PORT`
 
    keys=`echo "$stats" | egrep "STAT.*number" | cut -d ':' -f 2 | xargs echo`
 
    commands=""
    for key in $keys ; do 
        commands="stats cachedump $key 100 \n $commands"
    done
 
    echo -e "$commands quit " | nc $SERVER $PORT | grep ITEM

Hope that helps anybody.

Discussion Area - Leave a Comment