Contents

redis使用过程中会存在查询某类key的数量问题,较简单的办法为通过redis-cli结合keys进行操作,由于keys的工作机制导致线上一般禁用该指令,以下shell脚本通过scan实现统计功能。

使用:

1.保存以下shell脚本,如 redis_keycount.sh,增加执行权限

2.执行脚本附带key模式参数,如 ./redis_keycount.sh ‘my_key_*’

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#!/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!"

原来转自https://studygolang.com/articles/14275?fr=sidebar 感谢原作者

Contents