需求:获取redis实例中最大的top-N key
说明:由于redis 4.x才引入了memory usage keyname的语法。3.x不支持!
db_ip=5.5.5.101
db_port=6379
password=abc123
cursor=0
cnt=100
new_cursor=0
function get_key()
{
redis-cli -h $db_ip -p $db_port -a $password scan $1 count $cnt > scan_tmp_result
new_cursor=`sed -n '1p' scan_tmp_result`
sed -n '2,$p' scan_tmp_result > scan_result
}
function get_keysize()
{
cat $1 |while read line
do
key_size=`redis-cli -h $db_ip -p $db_port -a $password memory usage $line`
echo $line $key_size >> key_sizes.txt
done
}
get_key $cursor
get_keysize scan_result
while [ $cursor -ne $new_cursor ]
do
get_key $new_cursor
get_keysize scan_result
done
cat key_sizes.txt | sort -nrk2 | sed -n "1,$1p"
rm -rf scan_tmp_result
rm -rf scan_result
rm -rf key_sizes.txt
测试:
[redis@lxd-vm1 ~]$ sh get_bigkeys_top.sh 5 test2 12325 test 1589 c_9999 49 c_9998 49 c_9997 49