1 #!/bin/bash 2 # Redis 通過 scan 找出不過期的 key 3 # SCAN 命令是一個基於遊標的迭代器(cursor based iterator):SCAN 命令每次被調用之後,都會向用戶返回一個新的遊標,用戶在下次迭代時需要使用這個新遊標作爲 SCAN 命令的遊標參數,以此來延續之前的迭代過程。 4 # 注意:當 SCAN 命令的遊標參數被設置爲 0 時,服務器將開始一次新的迭代,而當服務器向用戶返回值爲 0 的遊標時,表示迭代已結束! 5 6 db_ip=10.100.41.148 # redis 連接IP 7 db_port=6379 # redis 端口 8 password='IootCdgN05srE' # redis 密碼 9 cursor=0 # 第一次遊標 10 cnt=100 # 每次迭代的數量 11 new_cursor=0 # 下一次遊標 12 13 redis-cli -c -h $db_ip -p $db_port -a $password scan $cursor count $cnt > scan_tmp_result 14 new_cursor=`sed -n '1p' scan_tmp_result` # 獲取下一次遊標 15 sed -n '2,$p' scan_tmp_result > scan_result # 獲取 key 16 cat scan_result |while read line # 循環遍歷所有 key 17 do 18 ttl_result=`redis-cli -c -h $db_ip -p $db_port -a $password ttl $line` # 獲取key過期時間 19 if [[ $ttl_result == -1 ]];then 20 #if [ $ttl_result -eq -1 ];then # 判斷過期時間,-1 是不過期 21 echo $line >> no_ttl.log # 追加到指定日誌 22 fi 23 done 24 25 while [ $cursor -ne $new_cursor ] # 若遊標不爲0,則證明沒有迭代完所有的key,繼續執行,直至遊標爲0 26 do 27 redis-cli -c -h $db_ip -p $db_port -a $password scan $new_cursor count $cnt > scan_tmp_result 28 new_cursor=`sed -n '1p' scan_tmp_result` 29 sed -n '2,$p' scan_tmp_result > scan_result 30 cat scan_result |while read line 31 do 32 ttl_result=`redis-cli -c -h $db_ip -p $db_port -a $password ttl $line` 33 if [[ $ttl_result == -1 ]];then 34 #if [ $ttl_result -eq -1 ];then 35 echo $line >> no_ttl.log 36 fi 37 done 38 done 39 rm -rf scan_tmp_result 40 rm -rf scan_result