SCAN 命令是一個基於游標的迭代器(cursor based iterator):SCAN 命令每次被調用之后,都會向用戶返回一個新的游標,用戶在下次迭代時需要使用這個新游標作為 SCAN 命令的游標參數,以此來延續之前的迭代過程。
注意:當 SCAN 命令的游標參數被設置為 0 時,服務器將開始一次新的迭代,而當服務器向用戶返回值為 0 的游標時,表示迭代已結束!
編寫腳本
#!/bin/bash
db_ip=127.0.0.1 # redis ip
db_port=6379 # redis 端口
password=ibalife # redis 密碼
cursor=0 # 第一次游標
cnt=100 # 每次迭代的數量
new_cursor=0 # 下一次游標
redis-cli -h $db_ip -p $db_port -a $password scan $cursor count $cnt > scan_tmp_result
new_cursor=`sed -n '1p' scan_tmp_result` # 獲取下一次游標
sed -n '2,$p' scan_tmp_result > scan_result # 獲取 keys
cat scan_result |while read line # 循環遍歷所有 keys
do
ttl_result=`redis-cli -h $db_ip -p $db_port -a $password ttl $line` # 獲取 key 過期時間
if [[ $ttl_result == -1 ]];then # 判斷過期時間,-1 是不過期
echo $line >> no_ttl.log # 追加到指定文件
fi
done
while [ $cursor -ne $new_cursor ] # 若 游標 不為 0 ,則證明沒有迭代完所有的 key,繼續執行
do
redis-cli -h $db_ip -p $db_port -a $password scan $new_cursor count $cnt > scan_tmp_result
new_cursor=`sed -n '1p' scan_tmp_result`
sed -n '2,$p' scan_tmp_result > scan_result
cat scan_result |while read line
do
ttl_result=`redis-cli -h $db_ip -p $db_port -a $password ttl $line`
if [[ $ttl_result == -1 ]];then
echo $line >> no_ttl.log
fi
done
done
rm -rf scan_tmp_result
rm -rf scan_result
注意,若你的 redis 占用內存很大,可以使用 tmux 命令新開一個窗口。最后所有符合的要求的 key 都會保存在 no_ttl.log 文件中