美文网首页
统计redis中key的数量

统计redis中key的数量

作者: 猪儿打滚 | 来源:发表于2021-04-22 08:22 被阅读0次

背景

需求:测试需要统计redis中某类key的数量

redis中可以使用keys命令来查看指定表中所有的key。因为 Redis 是单线程程序,顺序执行所有指令,其它指令必须等到当前的 keys 指令执行完了才可以继续,所以如果数目达到几百万时,keys这个命令就会导致 redis 服务卡顿。

shell脚本

#!/bin/bash

A=$0
B=${A##*/}
C=${B%.*}
running_file_name=$C
running_flag="run.$running_file_name"

REDIS_CLIENT='redis-cli -a xxxx -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!"
  • 执行
    sh key_count.sh "目标key的正则"

相关文章

网友评论

      本文标题:统计redis中key的数量

      本文链接:https://www.haomeiwen.com/subject/eocxrltx.html