redis使用过程中会存在查询某类key的数量问题,较简单的办法为通过redis-cli结合keys进行操作,由于keys的工作机制导致线上一般禁用该指令,以下shell脚本通过scan实现统计功能。
使用:
1.保存以下shell脚本,如 redis_keycount.sh,增加执行权限
2.执行脚本附带key模式参数,如 ./redis_keycount.sh 'my_key_*'
#!/bin/bash
A=$0
B=${A##*/}
C=${B%.*}
running_file_name=$C
running_flag="run.$running_file_name"
REDIS_CLIENT='redis-cli -h 0.0.0.0 -p 6379 -x'
function process {
echo $0
index=-1
count=0
step=100000
while ((index!=0))
do
if [ $index -le 0 ];then
index=0
fi
echo "scan $index match $1 count $step" | $REDIS_CLIENT > $running_file_name.cache
read index <<< `head -1 $running_file_name.cache`
read inc <<< `cat $running_file_name.cache | wc -l`
inc=$((inc - 1))
if [ $? -ne 0 ];then
break
fi
count=$((count + inc))
done
echo "$1 count:"$count
}
#
if [ $# -ne 1 ];then
echo "$0 <pars>"
exit 0
fi
#
if [ -f "$running_flag" ] ; then
echo "is running..."
exit 0
fi
#
touch $running_flag
#
echo "processing...."
echo $*
process $*
#
rm -rf $running_flag
#
echo "ok!"
有疑问加站长微信联系(非本文作者)