Redis 批量删除Key的脚本练习

2020-10-14  本文已影响0人  liuliuzo

造数脚本InitData.sh

#!/bin/bash
redis_list=("127.0.0.1:6379")
pkey_list=("ValuationRuleSummary" "ValuationRuleDetail" "MerchantValuation" "QueryValuationRules" "GetMerchantByUserId")
for info in ${redis_list[@]}
do
    echo "开始执行:$info"
    ip=`echo $info | cut -d \: -f 1`
    port=`echo $info | cut -d \: -f 2`
    for pkey in ${pkey_list[@]}
    do
        for i in `seq 0 10000`
        do
            echo $pkey"_"$i $i
            redis-cli -c -h $ip -p $port -a PASSWORD SET $pkey"_"$i $i
        done
    done
done
echo "完成"

Scan命令删除key的脚本deleteData.sh

#!/bin/bash
##redis master IP
host=$1
##redis port
pwd=$2
##key pattern
pattern=$3
##cursor start tag
cursor=0
##exit flag
signal=0
##cursor batch count
count=$4
  
##Loop to get the key and delete it
 
while [ $signal -ne 1 ]
    do
        echo "[$(date "+%Y-%m-%d %H:%M:%S")] cursor:${cursor}"
        ##Assign the result of redis scan to the variable
        re=$(redis-cli -h $host -p 6379 -a $pwd -c  scan $cursor count $count match $pattern)
        ##Line break as separator
        IFS=$'\n'
        ##Convert to array
        arr=($re)
        ##print the length of array
        echo "[$(date "+%Y-%m-%d %H:%M:%S")] match result len is:"${#arr[@]}
        ##The first element is the cursor value
        cursor=${arr[0]}
        ##If the cursor is 0, there is no key
        if [ $cursor -eq 0 ];then
            signal=1
        fi
        ##Loop array and delete key
    for key in ${arr[@]}
        do
            if [ $key != $cursor ];then
                ##Print deleted key
                echo "[$(date "+%Y-%m-%d %H:%M:%S")] delete key:"$key
                redis-cli -h $host -p 6379 -a $pwd -c del $key >/dev/null  2>&1
            fi
    done
done
echo "[$(date "+%Y-%m-%d %H:%M:%S")] done"

执行脚本命令

./redis_clean.sh "localhost" "password" "rule_detail_data_cache_*" 10000 >redis_delete.out
./redis_clean.sh "localhost" "password" "rule_data_accumulate_*" 10000 >redis_delete.out

命令参数说明:
$1:redis master server Ip地址
$2:redis password
$3:模糊匹配字符
$4:redis scan的batch大小
上一篇下一篇

猜你喜欢

热点阅读