场景
我们要统计redis中某类key的数量
背景
redis中可以使用keys命令来查看指定表中所有的key。但是 Redis 是单线程程序,顺序执行所有指令,其它指令必须等到当前的 keys 指令执行完了才可以继续,所以如果目标key的数量巨大,几十万上百万时,keys这个命令就会导致 redis 服务卡顿。所有keys通常在生产环境都是禁止使用的。那么我们要怎么来统计它的数量呢?
首先
快速在centos上安装redis-cli
wget http://download.redis.io/redis-stable.tar.gztar xvzf redis-stable.tar.gzcd redis-stablemake redis-clisudo cp src/redis-cli /usr/local/bin/
然后
就是redis_count.sh脚本
#!/bin/bashA=$0B=${A##*/}C=${B%.*}running_file_name=$Crunning_flag="run.$running_file_name"REDIS_CLIENT='redis-cli -h host -p 6379 -a password -n databaseIndex -x'# 这里3个参数需要修改host主机地址、password密码、databaseIndex数据库编号 0-255function process {echo $0index=-1count=0step=100000while ((index!=0))doif [ $index -le 0 ];thenindex=0fiecho "scan $index match $1 count $step" | $REDIS_CLIENT > $running_file_name.cacheread index <<< `head -1 $running_file_name.cache`read inc <<< `cat $running_file_name.cache | wc -l`inc=$((inc - 1))if [ $? -ne 0 ];thenbreakficount=$((count + inc))doneecho "$1 count:"$count}#if [ $# -ne 1 ];thenecho "$0 <pars>"exit 0fi#if [ -f "$running_flag" ] ; thenecho "is running..."exit 0fi#touch $running_flag#echo "processing...."echo $*process $*#rm -rf $running_flag#echo "ok!"
执行
/redis_count.sh "key的正则",例如:
/redis_count.sh ACCOUNT*
结果

文章转载自coding之光,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




