Redis Scan 命令用于迭代數據庫中的數據庫鍵。
SCAN 返回一個包含兩個元素的數組, 第一個元素是用于進行下一次迭代的新游標, 而第二個元素則是一個數組, 這個數組中包含了所有被迭代的元素。如果新游標返回 0 表示迭代已結束。
相關命令:
SSCAN 命令用于迭代集合鍵中的元素。
HSCAN 命令用于迭代哈希鍵中的鍵值對。
ZSCAN 命令用于迭代有序集合中的元素(包括元素成員和元素分值)。
# SCAN 命令是一個基于游標的迭代器(cursor based iterator):SCAN 命令每次被調用之后,都會向用戶返回一個新的游標,用戶在下次迭代時需要使用這個新游標作為 SCAN 命令的游標參數,以此來延續之前的迭代過程。
# 注意:當 SCAN 命令的游標參數被設置為 0 時,服務器將開始一次新的迭代,而當服務器向用戶返回值為 0 的游標時,表示迭代已結束!
# vim redis_no_ttl_key.sh
#!/bin/bash
# Redis 通過 scan 找出不過期的 key
# SCAN 命令是一個基于游標的迭代器(cursor based iterator):SCAN 命令每次被調用之后,都會向用戶返回一個新的游標,用戶在下次迭代時需要使用這個新游標作為 SCAN 命令的游標參數,以此來延續之前的迭代過程。
# 注意:當 SCAN 命令的游標參數被設置為 0 時,服務器將開始一次新的迭代,而當服務器向用戶返回值為 0 的游標時,表示迭代已結束!
db_ip=10.100.41.148 # redis 連接IP
db_port=6379 # redis 端口
password='IootCdgN05srE' # redis 密碼
cursor=0 # 第一次游標
cnt=100 # 每次迭代的數量
new_cursor=0 # 下一次游標
redis-cli -c -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 # 獲取 key
cat scan_result |while read line # 循環遍歷所有 key
do
ttl_result=`redis-cli -c -h $db_ip -p $db_port -a $password ttl $line` # 獲取key過期時間
if [[ $ttl_result == -1 ]];then
#if [ $ttl_result -eq -1 ];then # 判斷過期時間,-1 是不過期
echo $line >> no_ttl.log # 追加到指定日志
fi
done
while [ $cursor -ne $new_cursor ] # 若游標不為0,則證明沒有迭代完所有的key,繼續執行,直至游標為0
do
redis-cli -c -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 -c -h $db_ip -p $db_port -a $password ttl $line`
if [[ $ttl_result == -1 ]];then
#if [ $ttl_result -eq -1 ];then
echo $line >> no_ttl.log
fi
done
done
rm -rf scan_tmp_result
rm -rf scan_result
到此這篇關于Redis通過scan查找不過期的 key的文章就介紹到這了,更多相關Redis scan 查找 key內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- Redis遍歷所有key的兩個命令(KEYS 和 SCAN)
- redis keys與scan命令的區別說明
- 在RedisTemplate中使用scan代替keys指令操作
- redis 用scan指令 代替keys指令(詳解)